Package freenet.support

Examples of freenet.support.HTMLNode


    }
    return reasonCell;
  }

  public static HTMLNode createProgressCell(boolean advancedMode, boolean started, COMPRESS_STATE compressing, int fetched, int failed, int fatallyFailed, int min, int total, boolean finalized, boolean upload) {
    HTMLNode progressCell = new HTMLNode("td", "class", "request-progress");
    if (!started) {
      progressCell.addChild("#", l10n("starting"));
      return progressCell;
    }
    if(compressing == COMPRESS_STATE.WAITING && advancedMode) {
      progressCell.addChild("#", l10n("awaitingCompression"));
      return progressCell;
    }
    if(compressing != COMPRESS_STATE.WORKING) {
      progressCell.addChild("#", l10n("compressing"));
      return progressCell;
    }

    //double frac = p.getSuccessFraction();
    if (!advancedMode || total < min /* FIXME why? */) {
      total = min;
    }

    if ((fetched < 0) || (total <= 0)) {
      progressCell.addChild("span", "class", "progress_fraction_unknown", l10n("unknown"));
    } else {
      int fetchedPercent = (int) (fetched / (double) total * 100);
      int failedPercent = (int) (failed / (double) total * 100);
      int fatallyFailedPercent = (int) (fatallyFailed / (double) total * 100);
      int minPercent = (int) (min / (double) total * 100);
      HTMLNode progressBar = progressCell.addChild("div", "class", "progressbar");
      progressBar.addChild("div", new String[] { "class", "style" }, new String[] { "progressbar-done", "width: " + fetchedPercent + "%;" });

      if (failed > 0)
        progressBar.addChild("div", new String[] { "class", "style" }, new String[] { "progressbar-failed", "width: " + failedPercent + "%;" });
      if (fatallyFailed > 0)
        progressBar.addChild("div", new String[] { "class", "style" }, new String[] { "progressbar-failed2", "width: " + fatallyFailedPercent + "%;" });
      if ((fetched + failed + fatallyFailed) < min)
        progressBar.addChild("div", new String[] { "class", "style" }, new String[] { "progressbar-min", "width: " + (minPercent - fetchedPercent) + "%;" });

      NumberFormat nf = NumberFormat.getInstance();
      nf.setMaximumFractionDigits(1);
      String prefix = '('+Integer.toString(fetched) + "/ " + Integer.toString(min)+"): ";
      if (finalized) {
        progressBar.addChild("div", new String[] { "class", "title" }, new String[] { "progress_fraction_finalized", prefix + l10n("progressbarAccurate") }, nf.format((int) ((fetched / (double) min) * 1000) / 10.0) + '%');
      } else {
        String text = nf.format((int) ((fetched / (double) min) * 1000) / 10.0)+ '%';
        if(!finalized)
          text = "" + fetched + " ("+text+"??)";
        progressBar.addChild("div", new String[] { "class", "title" }, new String[] { "progress_fraction_not_finalized", prefix + NodeL10n.getBase().getString(upload ? "QueueToadlet.uploadProgressbarNotAccurate" : "QueueToadlet.progressbarNotAccurate") }, text);
      }
    }
    return progressCell;
  }
View Full Code Here


      if(mimeType.compareTo("application/xhtml+xml")==0){
        mimeType="text/html";
      }
      if(horribleEvilHack(data) && !(mimeType.startsWith("application/rss+xml"))) {
        PageNode page = context.getPageMaker().getPageNode(l10n("dangerousRSSTitle"), context);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;

        HTMLNode infobox = contentNode.addChild("div", "class", "infobox infobox-alert");
        infobox.addChild("div", "class", "infobox-header", l10n("dangerousRSSSubtitle"));
        HTMLNode infoboxContent = infobox.addChild("div", "class", "infobox-content");
        infoboxContent.addChild("#", NodeL10n.getBase().getString("FProxyToadlet.dangerousRSS", new String[] { "type" }, new String[] { mimeType }));
        infoboxContent.addChild("p", l10n("options"));
        HTMLNode optionList = infoboxContent.addChild("ul");
        HTMLNode option = optionList.addChild("li");

        NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openPossRSSAsPlainText", new String[] { "link", "bold" },
            new HTMLNode[] {
            HTMLNode.link(basePath+key.toString()+"?type=text/plain&force="+getForceValue(key,now)+extrasNoMime),
            HTMLNode.STRONG
View Full Code Here

        filterChecked = false;
    }
    //Display FProxy option to download to disk if the user isn't at maximum physical threat level
    //and hasn't disabled downloading to disk.
    if (threatLevel != PHYSICAL_THREAT_LEVEL.MAXIMUM && !core.isDownloadDisabled()) {
      HTMLNode option = optionList.addChild("li");
      HTMLNode optionForm = ctx.addFormChild(option, "/downloads/", "tooBigQueueForm");
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "key", key.toString() });
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "return-type", "disk" });
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "persistence", "forever" });
      if (mimeType != null && !mimeType.equals("")) {
        optionForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "hidden", "type", mimeType });
      }
      optionForm.addChild("input", new String[] { "type", "name", "value" },
              new String[] { "submit", "download", l10n("downloadInBackgroundToDiskButton") });
      String downloadLocation = core.getDownloadsDir().getAbsolutePath();
      //If the download directory isn't allowed, yet downloading is, at least one directory must
      //have been explicitly defined, so take the first one.
      if (!core.allowDownloadTo(core.getDownloadsDir())) {
        downloadLocation = core.getAllowedDownloadDirs()[0].getAbsolutePath();
      }
      NodeL10n.getBase().addL10nSubstitution(optionForm, "FProxyToadlet.downloadInBackgroundToDisk",
              new String[] { "dir", "page" },
              new HTMLNode[] { new HTMLNode("input",
                      new String[] { "type", "name", "value", "maxlength", "size" },
                      new String[] { "text", "path", downloadLocation,
                              Integer.toString(QueueToadlet.MAX_FILENAME_LENGTH),
                              String.valueOf(downloadLocation.length())}),
                      DOWNLOADS_LINK });
      optionForm.addChild("#", " ");
      NodeL10n.getBase().addL10nSubstitution(optionForm,
              "FProxyToadlet.downloadToDiskWarningNotFiltered",
              new String[] {"bold" }, new HTMLNode[] { HTMLNode.STRONG });
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "submit", "select-location",
                NodeL10n.getBase().getString("QueueToadlet.browseToChange")+"..."} );
      if(!dontShowFilter) {
        HTMLNode filterControl = optionForm.addChild("div", l10n("filterData"));
        HTMLNode f = filterControl.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "checkbox", "filterData", "filterData"});
        if(filterChecked) f.addAttribute("checked", "checked");
        filterControl.addChild("div", l10n("filterDataMessage"));
      }
      if (threatLevel == PHYSICAL_THREAT_LEVEL.HIGH) {
        optionForm.addChild("br");
        NodeL10n.getBase().addL10nSubstitution(optionForm,
                "FProxyToadlet.downloadToDiskSecurityWarning",
                new String[] {"bold" }, new HTMLNode[] { HTMLNode.STRONG });
        //optionForm.addChild("#", l10n("downloadToDiskSecurityWarning") + " ");
      }
    }

    //Display fetch option if not at low physical security or the user has disabled downloading to disk.
    if (threatLevel != PHYSICAL_THREAT_LEVEL.LOW || core.isDownloadDisabled()) {
      HTMLNode option = optionList.addChild("li");
      HTMLNode optionForm = ctx.addFormChild(option, "/downloads/", "tooBigQueueForm");
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "key", key.toString() });
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "return-type", "direct" });
      optionForm.addChild("input",
              new String[] { "type", "name", "value" },
              new String[] { "hidden", "persistence", "forever" });
      if (mimeType != null && !mimeType.equals("")) {
        optionForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "hidden", "type", mimeType });
      }
      optionForm.addChild("input", new String[] { "type", "name", "value" },
              new String[] { "submit", "download", l10n("downloadInBackgroundToTempSpaceButton") });
      NodeL10n.getBase().addL10nSubstitution(optionForm,
              "FProxyToadlet.downloadInBackgroundToTempSpace",
              new String[] { "page", "bold" }, new HTMLNode[] { DOWNLOADS_LINK, HTMLNode.STRONG });
      if(!dontShowFilter) {
        HTMLNode filterControl = optionForm.addChild("div", l10n("filterData"));
        HTMLNode f = filterControl.addChild("input",
            new String[] { "type", "name", "value" },
            new String[] { "checkbox", "filterData", "filterData"});
        if(filterChecked) f.addAttribute("checked", "checked");
        filterControl.addChild("div", l10n("filterDataMessage"));
      }
    }
  }
View Full Code Here

    FreenetURI key;
    try {
      key = new FreenetURI(ks);
    } catch (MalformedURLException e) {
      PageNode page = ctx.getPageMaker().getPageNode(l10n("invalidKeyTitle"), ctx);
      HTMLNode pageNode = page.outer;
      HTMLNode contentNode = page.content;

      HTMLNode errorInfobox = contentNode.addChild("div", "class", "infobox infobox-error");
      errorInfobox.addChild("div", "class", "infobox-header", NodeL10n.getBase().getString("FProxyToadlet.invalidKeyWithReason", new String[] { "reason" }, new String[] { e.toString() }));
      HTMLNode errorContent = errorInfobox.addChild("div", "class", "infobox-content");
      errorContent.addChild("#", l10n("expectedKeyButGot"));
      errorContent.addChild("code", ks);
      errorContent.addChild("br");
      errorContent.addChild(ctx.getPageMaker().createBackLink(ctx, l10n("goBack")));
      errorContent.addChild("br");
      addHomepageLink(errorContent);

      this.writeHTMLReply(ctx, 400, l10n("invalidKeyTitle"), pageNode.generate());
      return;
    }

    FetchContext fctx = getFetchContext(maxSize);
    // max-size=-1 => use default
    maxSize = fctx.maxOutputLength;

    //We should run the ContentFilter by default
    String forceString = httprequest.getParam("force");
    long now = System.currentTimeMillis();
    boolean force = false;
    if(forceString != null) {
      if(forceString.equals(getForceValue(key, now)) ||
          forceString.equals(getForceValue(key, now-FORCE_GRAIN_INTERVAL)))
        force = true;
    }
    if(restricted)
      maxRetries = -2;
    if(maxRetries >= -1) {
      fctx.maxNonSplitfileRetries = maxRetries;
      fctx.maxSplitfileBlockRetries = maxRetries;
    }
    if (!force && !httprequest.isParameterSet("forcedownload")) fctx.filterData = true;
    else if(logMINOR) Logger.minor(this, "Content filter disabled via request parameter");
    //Load the fetch context with the callbacks needed for web-pushing, if enabled
    if(container.enableInlinePrefetch()) {
      fctx.prefetchHook = new FoundURICallback() {

        List<FreenetURI> uris = new ArrayList<FreenetURI>();
       
        @Override
        public void foundURI(FreenetURI uri) {
          // Ignore
        }

        @Override
        public void foundURI(FreenetURI uri, boolean inline) {
          if(!inline) return;
          if(logMINOR) Logger.minor(this, "Prefetching "+uri);
          synchronized(this) {
            if(uris.size() < MAX_PREFETCH)
              // FIXME Maybe we should do this randomly, but since it's a DoS protection (in an obscure feature), if so we should do it in constant space!
              uris.add(uri);
          }
        }

        @Override
        public void onText(String text, String type, URI baseURI) {
          // Ignore
        }

        @Override
        public void onFinishedPage() {
          core.node.executor.execute(new Runnable() {

            @Override
            public void run() {
              for(FreenetURI uri : uris) {
                client.prefetch(uri, SECONDS.toMillis(60), 512*1024, prefetchAllowedTypes);
              }
            }
           
          });
        }

      };

    }
    if(container.isFProxyWebPushingEnabled()) fctx.tagReplacer = new PushingTagReplacerCallback(core.getFProxy().fetchTracker, defaultMaxSize, ctx);

    String requestedMimeType = httprequest.getParam("type", null);
    fctx.overrideMIME = requestedMimeType;
    String override = (requestedMimeType == null) ? "" : "?type="+URLEncoder.encode(requestedMimeType,true);
    String maybeCharset = httprequest.isParameterSet("maybecharset") ? httprequest.getParam("maybecharset", null) : null;
    fctx.charset = maybeCharset;
    if(override.equals("") && maybeCharset != null)
      override = "?maybecharset="+URLEncoder.encode(maybeCharset, true);
    // No point passing ?force= across a redirect, since the key will change.
    // However, there is every point in passing ?forcedownload.
    if(httprequest.isParameterSet("forcedownload")) {
      if(override.length() == 0) override = "?forcedownload";
      else override = override+"&forcedownload";
    }

    Bucket data = null;
    String mimeType = null;
    String referer = sanitizeReferer(ctx);
    FetchException fe = null;


    FProxyFetchResult fr = null;

      FProxyFetchWaiter fetch = null;
      try {
        fetch = fetchTracker.makeFetcher(key, maxSize, fctx, ctx.getReFilterPolicy());
      } catch (FetchException e) {
            fe = e;
      }
      if(fetch != null)
      while(true) {
      fr = fetch.getResult(!canSendProgress);
      if(fr.hasData()) {

        if(fr.getFetchCount() > 1 && !fr.hasWaited() && fr.getFetchCount() > 1 && key.isUSK() && context.uskManager.lookupKnownGood(USK.create(key)) > key.getSuggestedEdition()) {
          Logger.normal(this, "Loading later edition...");
          fetch.progress.requestImmediateCancel();
          fr = null;
          fetch = null;
          try {
            fetch = fetchTracker.makeFetcher(key, maxSize, fctx, ctx.getReFilterPolicy());
          } catch (FetchException e) {
                            fe = e;
          }
          if(fetch == null) break;
          continue;
        }

        if(logMINOR) Logger.minor(this, "Found data");
        data = new NoFreeBucket(fr.data);
        mimeType = fr.mimeType;
        fetch.close(); // Not waiting any more, but still locked the results until sent
        break;
      } else if(fr.failed != null) {
        if(logMINOR) Logger.minor(this, "Request failed");
        fe = fr.failed;
        fetch.close(); // Not waiting any more, but still locked the results until sent
        break;
      } else if(canSendProgress) {
        if(logMINOR) Logger.minor(this, "Still in progress");
        // Still in progress
        boolean isJsEnabled=ctx.getContainer().isFProxyJavascriptEnabled() && ua != null && !ua.contains("AppleWebKit/");
        boolean isWebPushingEnabled = false;
        PageNode page = ctx.getPageMaker().getPageNode(l10n("fetchingPageTitle"), ctx);
        HTMLNode pageNode = page.outer;
        String location = getLink(key, requestedMimeType, maxSize, httprequest.getParam("force", null), httprequest.isParameterSet("forcedownload"), maxRetries, overrideSize);
        HTMLNode headNode=page.headNode;
        if(isJsEnabled){
          //If the user has enabled javascript, we add a <noscript> http refresh(if he has disabled it in the browser)
          headNode.addChild("noscript").addChild("meta", "http-equiv", "Refresh").addAttribute("content", "2;URL=" + location);
            // If pushing is disabled, but js is enabled, then we add the original progresspage.js
            if ((isWebPushingEnabled = ctx.getContainer().isFProxyWebPushingEnabled()) == false) {
              HTMLNode scriptNode = headNode.addChild("script", "//abc");
              scriptNode.addAttribute("type", "text/javascript");
              scriptNode.addAttribute("src", "/static/js/progresspage.js");
            }
        }else{
          //If he disabled it, we just put the http refresh meta, without the noscript
          headNode.addChild("meta", "http-equiv", "Refresh").addAttribute("content", "2;URL=" + location);
        }
        HTMLNode contentNode = page.content;
        HTMLNode infobox = contentNode.addChild("div", "class", "infobox infobox-information");
        infobox.addChild("div", "class", "infobox-header", l10n("fetchingPageBox"));
        HTMLNode infoboxContent = infobox.addChild("div", "class", "infobox-content");
        infoboxContent.addAttribute("id", "infoContent");
        infoboxContent.addChild(new ProgressInfoElement(fetchTracker, key, fctx, maxSize, ctx.isAdvancedModeEnabled(), ctx, isWebPushingEnabled));


        HTMLNode table = infoboxContent.addChild("table", "border", "0");
        HTMLNode progressCell = table.addChild("tr").addChild("td", "class", "request-progress");
        if(fr.totalBlocks <= 0)
          progressCell.addChild("#", NodeL10n.getBase().getString("QueueToadlet.unknown"));
        else {
          progressCell.addChild(new ProgressBarElement(fetchTracker,key,fctx,maxSize,ctx, isWebPushingEnabled));
        }

        infobox = contentNode.addChild("div", "class", "infobox infobox-information");
        infobox.addChild("div", "class", "infobox-header", l10n("fetchingPageOptions"));
        infoboxContent = infobox.addChild("div", "class", "infobox-content");

        HTMLNode optionList = infoboxContent.addChild("ul");
        optionList.addChild("li").addChild("p", l10n("progressOptionZero"));

        addDownloadOptions(ctx, optionList, key, mimeType, false, false, core);

        optionList.addChild("li").addChild(ctx.getPageMaker().createBackLink(ctx, l10n("goBackToPrev")));
        optionList.addChild("li").addChild("a", new String[] { "href", "title" },
            new String[] { "/", NodeL10n.getBase().getString("Toadlet.homepage") }, l10n("abortToHomepage"));

        MultiValueTable<String, String> retHeaders = new MultiValueTable<String, String>();
        //retHeaders.put("Refresh", "2; url="+location);
        writeHTMLReply(ctx, 200, "OK", retHeaders, pageNode.generate());
        fr.close();
        fetch.close();
        return;
      } else if(fr != null)
        fr.close();
      }

    try {
      if(logMINOR)
        Logger.minor(this, "FProxy fetching "+key+" ("+maxSize+ ')');
      if(data == null && fe == null) {
        boolean needsFetch=true;
        //If we don't have the data, then check if an FProxyFetchInProgress has. It can happen when one FetchInProgress downloaded an image
        //asynchronously, then loads it. This way a FetchInprogress will have the full image, and no need to block.
        FProxyFetchInProgress progress=fetchTracker.getFetchInProgress(key, maxSize, fctx);
        if(progress!=null){
          FProxyFetchWaiter waiter=null;
          FProxyFetchResult result=null;
          try{
            waiter=progress.getWaiter();
            result=waiter.getResult(false);
            if(result.failed==null && result.data!=null){
              mimeType=result.mimeType;
              data=result.data;
              data=ctx.getBucketFactory().makeBucket(result.data.size());
              BucketTools.copy(result.data, data);
              needsFetch=false;
            }
          }finally{
            if(waiter!=null){
              progress.close(waiter);
            }
            if(result!=null){
              progress.close(result);
            }
          }
        }
        if(needsFetch){
          //If we don't have the data, then we need to fetch it and block until it is available
          FetchResult result = fetch(key, maxSize, new RequestClient() {
            @Override
            public boolean persistent() {
              return false;
            }
            @Override
            public boolean realTimeFlag() {
              return true;
            } }, fctx);

          // Now, is it safe?

          data = result.asBucket();
          mimeType = result.getMimeType();
        }
      } else if(fe != null) throw fe;

      handleDownload(ctx, data, ctx.getBucketFactory(), mimeType, requestedMimeType, forceString, httprequest.isParameterSet("forcedownload"), "/", key, "&max-size="+maxSizeDownload, referer, true, ctx, core, fr != null, maybeCharset);
    } catch (FetchException e) {
      //Handle exceptions thrown from the ContentFilter
      String msg = e.getMessage();
      if(logMINOR) {
        Logger.minor(this, "Failed to fetch "+uri+" : "+e);
      }
      if(e.newURI != null) {
        if(accept != null && (accept.startsWith("text/css") || accept.startsWith("image/")) && recursion++ < MAX_RECURSION) {
          // If it's an image or a CSS fetch, auto-follow the redirect, up to a limit.
          String link = getLink(e.newURI, requestedMimeType, maxSize, httprequest.getParam("force", null), httprequest.isParameterSet("forcedownload"), maxRetries, overrideSize);
          try {
            uri = new URI(link);
            innerHandleMethodGET(uri, httprequest, ctx, recursion);
            return;
          } catch (URISyntaxException e1) {
            Logger.error(this, "Caught "+e1+" parsing new link "+link, e1);
          }
        }
        Toadlet.writePermanentRedirect(ctx, msg,
          getLink(e.newURI, requestedMimeType, maxSize, httprequest.getParam("force", null), httprequest.isParameterSet("forcedownload"), maxRetries, overrideSize));
      } else if(e.mode == FetchExceptionMode.TOO_BIG) {
        PageNode page = ctx.getPageMaker().getPageNode(l10n("fileInformationTitle"), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;

        HTMLNode infobox = contentNode.addChild("div", "class", "infobox infobox-information");
        infobox.addChild("div", "class", "infobox-header", l10n("largeFile"));
        HTMLNode infoboxContent = infobox.addChild("div", "class", "infobox-content");
        HTMLNode fileInformationList = infoboxContent.addChild("ul");
        HTMLNode option = fileInformationList.addChild("li");
        option.addChild("#", (l10n("filenameLabel") + ' '));
        option.addChild("a", "href", '/' + key.toString(), getFilename(key, e.getExpectedMimeType()));

        String mime = writeSizeAndMIME(fileInformationList, e);

        infobox = contentNode.addChild("div", "class", "infobox infobox-information");
        infobox.addChild("div", "class", "infobox-header", l10n("explanationTitle"));
        infoboxContent = infobox.addChild("div", "class", "infobox-content");
        infoboxContent.addChild("#", l10n("largeFileExplanationAndOptions"));
        HTMLNode optionList = infoboxContent.addChild("ul");
        //HTMLNode optionTable = infoboxContent.addChild("table", "border", "0");
        if(!restricted) {
          option = optionList.addChild("li");
          HTMLNode optionForm = option.addChild("form", new String[] { "action", "method" }, new String[] {'/' + key.toString(), "get" });
          optionForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "max-size", String.valueOf(e.expectedSize == -1 ? Long.MAX_VALUE : e.expectedSize*2) });
          if (requestedMimeType != null)
            optionForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "type", requestedMimeType });
          if(maxRetries >= -1)
            optionForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "max-retries", Integer.toString(maxRetries) });
          optionForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "fetch", l10n("fetchLargeFileAnywayAndDisplayButton") });
          optionForm.addChild("#", " - " + l10n("fetchLargeFileAnywayAndDisplay"));
          addDownloadOptions(ctx, optionList, key, mime, false, false, core);
        }


        //optionTable.addChild("tr").addChild("td", "colspan", "2").addChild("a", new String[] { "href", "title" }, new String[] { "/", NodeL10n.getBase().getString("Toadlet.homepage") }, l10n("abortToHomepage"));
        optionList.addChild("li").addChild("a", new String[] { "href", "title" }, new String[] { "/", NodeL10n.getBase().getString("Toadlet.homepage") }, l10n("abortToHomepage"));

        //option = optionTable.addChild("tr").addChild("td", "colspan", "2");
        optionList.addChild("li").addChild(ctx.getPageMaker().createBackLink(ctx, l10n("goBackToPrev")));

        writeHTMLReply(ctx, 200, "OK", pageNode.generate());
      } else {
        PageNode page = ctx.getPageMaker().getPageNode(e.getShortMessage(), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;

        HTMLNode infobox = contentNode.addChild("div", "class", "infobox infobox-error");
        infobox.addChild("div", "class", "infobox-header", l10n("errorWithReason", "error", e.getShortMessage()));
        HTMLNode infoboxContent = infobox.addChild("div", "class", "infobox-content");
        HTMLNode fileInformationList = infoboxContent.addChild("ul");
        HTMLNode option = fileInformationList.addChild("li");
        option.addChild("#", (l10n("filenameLabel") + ' '));
        option.addChild("a", "href", '/' + key.toString(), getFilename(key, e.getExpectedMimeType()));

        String mime = writeSizeAndMIME(fileInformationList, e);
        infobox = contentNode.addChild("div", "class", "infobox infobox-error");
        infobox.addChild("div", "class", "infobox-header", l10n("explanationTitle"));
        UnsafeContentTypeException filterException = null;
        if(e.getCause() != null && e.getCause() instanceof UnsafeContentTypeException) {
          filterException = (UnsafeContentTypeException)e.getCause();
        }
        infoboxContent = infobox.addChild("div", "class", "infobox-content");
        if(filterException == null)
          infoboxContent.addChild("p", l10n("unableToRetrieve"));
        else
          infoboxContent.addChild("p", l10n("unableToSafelyDisplay"));
        if(e.isFatal() && filterException == null)
          infoboxContent.addChild("p", l10n("errorIsFatal"));
        infoboxContent.addChild("p", msg);
        if(filterException != null) {
          if(filterException.details() != null) {
            HTMLNode detailList = infoboxContent.addChild("ul");
            for(String detail : filterException.details()) {
              detailList.addChild("li", detail);
            }
          }
        }
        if(e.errorCodes != null) {
          infoboxContent.addChild("p").addChild("pre").addChild("#", e.errorCodes.toVerboseString());
        }

        infobox = contentNode.addChild("div", "class", "infobox infobox-error");
        infobox.addChild("div", "class", "infobox-header", l10n("options"));
        infoboxContent = infobox.addChild("div", "class", "infobox-content");

        HTMLNode optionList = infoboxContent.addChild("ul");

        PluginInfoWrapper keyUtil;
        if((e.mode == FetchExceptionMode.NOT_IN_ARCHIVE || e.mode == FetchExceptionMode.NOT_ENOUGH_PATH_COMPONENTS)) {
          // first look for the newest version
          if ((keyUtil = core.node.pluginManager.getPluginInfo("plugins.KeyUtils.KeyUtilsPlugin")) != null) {
            option = optionList.addChild("li");
            if (keyUtil.getPluginLongVersion() < 5010)
              NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openWithKeyExplorer", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/KeyUtils/?automf=true&key=" + key.toString()) });
            else {
              NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openWithKeyExplorer", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/KeyUtils/?key=" + key.toString()) });
              option = optionList.addChild("li");
              NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openWithSiteExplorer", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/KeyUtils/Site?key=" + key.toString()) });
            }
          } else if ((keyUtil = core.node.pluginManager.getPluginInfo("plugins.KeyExplorer.KeyExplorer")) != null) {
            option = optionList.addChild("li");
            if (keyUtil.getPluginLongVersion() > 4999)
              NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openWithKeyExplorer", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/KeyExplorer/?automf=true&key=" + key.toString())});
            else
              NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openWithKeyExplorer", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/plugins/plugins.KeyExplorer.KeyExplorer/?key=" + key.toString())});
          }
        }
        if(filterException != null) {
          if((mime.equals("application/x-freenet-index")) && (core.node.pluginManager.isPluginLoaded("plugins.ThawIndexBrowser.ThawIndexBrowser"))) {
            option = optionList.addChild("li");
            NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openAsThawIndex", new String[] { "link" }, new HTMLNode[] { HTMLNode.link("/plugins/plugins.ThawIndexBrowser.ThawIndexBrowser/?key=" + key.toString()).addChild("b") });
          }
          option = optionList.addChild("li");
          // FIXME: is this safe? See bug #131
          MediaType textMediaType = new MediaType("text/plain");
          textMediaType.setParameter("charset", (e.getExpectedMimeType() != null) ? MediaType.getCharsetRobust(e.getExpectedMimeType()) : null);
          NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openAsText", new String[] { "link" }, new HTMLNode[] { HTMLNode.link(getLink(key, textMediaType.toString(), maxSize, null, false, maxRetries, overrideSize)) });
          option = optionList.addChild("li");
          NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openForceDisk", new String[] { "link" }, new HTMLNode[] { HTMLNode.link(getLink(key, mime, maxSize, null, true, maxRetries, overrideSize)) });
          if(!(mime.equals("application/octet-stream") || mime.equals("application/x-msdownload") || !DefaultMIMETypes.isPlausibleMIMEType(mime))) {
            option = optionList.addChild("li");
            NodeL10n.getBase().addL10nSubstitution(option, "FProxyToadlet.openForce", new String[] { "link", "mime" }, new HTMLNode[] { HTMLNode.link(getLink(key, mime, maxSize, getForceValue(key, now), false, maxRetries, overrideSize)), HTMLNode.text(HTMLEncoder.encode(mime))});
          }
        }

        if((!e.isFatal() || filterException != null) && (ctx.isAllowedFullAccess() || !container.publicGatewayMode())) {
          addDownloadOptions(ctx, optionList, key, mimeType, filterException != null, filterException != null, core);
          if(filterException == null)
            optionList.addChild("li").
              addChild("a", "href", getLink(key, requestedMimeType, maxSize, httprequest.getParam("force", null),
                  httprequest.isParameterSet("forcedownload"), maxRetries, overrideSize)).addChild("#", l10n("retryNow"));
        }

        optionList.addChild("li").addChild("a", new String[] { "href", "title" }, new String[] { "/", NodeL10n.getBase().
            getString("Toadlet.homepage") }, l10n("abortToHomepage"));

        optionList.addChild("li").addChild(ctx.getPageMaker().createBackLink(ctx, l10n("goBackToPrev")));
        this.writeHTMLReply(ctx, (e.mode == FetchExceptionMode.NOT_IN_ARCHIVE) ? 404 : 500 /* close enough - FIXME probably should depend on status code */,
            "Internal Error", pageNode.generate());
      }
    } catch (SocketException e) {
      // Probably irrelevant
View Full Code Here

      if(req.isPartSet("node_" + peer.hashCode()))
        peer.sendBookmarkFeed(item.getURI(), item.getName(), publicDescription, item.hasAnActivelink());
  }

  private HTMLNode getBookmarksList(BookmarkManager bookmarkManager) {
    HTMLNode bookmarks = new HTMLNode("ul", "id", "bookmarks");

    HTMLNode root = bookmarks.addChild("li", "class", "cat root", "/");
    HTMLNode actions = new HTMLNode("span", "class", "actions");
    String addBookmark = NodeL10n.getBase().getString("BookmarkEditorToadlet.addBookmark");
    String addCategory = NodeL10n.getBase().getString("BookmarkEditorToadlet.addCategory");
    String paste = NodeL10n.getBase().getString("BookmarkEditorToadlet.paste");
    actions.addChild("a", "href", "?action=addItem&bookmark=/").addChild("img", new String[]{"src", "alt", "title"}, new String[]{"/static/icon/bookmark-new.png", addBookmark, addBookmark});
    actions.addChild("a", "href", "?action=addCat&bookmark=/").addChild("img", new String[]{"src", "alt", "title"}, new String[]{"/static/icon/folder-new.png", addCategory, addCategory});

    if(cutedPath != null && !"/".equals(bookmarkManager.parentPath(cutedPath)))
      actions.addChild("a", "href", "?action=paste&bookmark=/").addChild("img", new String[]{"src", "alt", "title"}, new String[]{"/static/icon/paste.png", paste, paste});

    root.addChild(actions);
    addCategoryToList(BookmarkManager.MAIN_CATEGORY, "/", root.addChild("ul"), bookmarkManager);

    return bookmarks;
View Full Code Here

    PageMaker pageMaker = ctx.getPageMaker();
    BookmarkManager bookmarkManager = ctx.getBookmarkManager();
    String editorTitle = NodeL10n.getBase().getString("BookmarkEditorToadlet.title");
    String error = NodeL10n.getBase().getString("BookmarkEditorToadlet.error");
    PageNode page = pageMaker.getPageNode(editorTitle, ctx);
    HTMLNode pageNode = page.outer;
    HTMLNode content = page.content;
    String originalBookmark = req.getParam("bookmark");
    if(req.getParam("action").length() > 0 && originalBookmark.length() > 0) {
      String action = req.getParam("action");
      String bookmarkPath;
      try {
        bookmarkPath = URLDecoder.decode(originalBookmark, false);
      } catch(URLEncodedFormatException e) {
        pageMaker.getInfobox("infobox-error", error, content, "bookmark-url-decode-error", false).
          addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.urlDecodeError"));
        writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      }
      Bookmark bookmark;

      if(bookmarkPath.endsWith("/"))
        bookmark = bookmarkManager.getCategoryByPath(bookmarkPath);
      else
        bookmark = bookmarkManager.getItemByPath(bookmarkPath);

      if(bookmark == null) {
        pageMaker.getInfobox("infobox-error", error, content, "bookmark-does-not-exist", false).
          addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.bookmarkDoesNotExist", new String[]{"bookmark"}, new String[]{bookmarkPath}));
        this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      } else
        if("del".equals(action)) {

          String[] bm = new String[]{"bookmark"};
          String[] path = new String[]{bookmarkPath};
          String queryTitle = NodeL10n.getBase().getString("BookmarkEditorToadlet." + ((bookmark instanceof BookmarkItem) ? "deleteBookmark" : "deleteCategory"));
          HTMLNode infoBoxContent = pageMaker.getInfobox("infobox-query", queryTitle, content, "bookmark-delete", false);

          String query = NodeL10n.getBase().getString("BookmarkEditorToadlet." + ((bookmark instanceof BookmarkItem) ? "deleteBookmarkConfirm" : "deleteCategoryConfirm"), bm, path);
          infoBoxContent.addChild("p").addChild("#", query);

          HTMLNode confirmForm = ctx.addFormChild(infoBoxContent, "", "confirmDeleteForm");
          confirmForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "bookmark", bookmarkPath});
          confirmForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "cancel", NodeL10n.getBase().getString("Toadlet.cancel")});
          confirmForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "confirmdelete", NodeL10n.getBase().getString("BookmarkEditorToadlet.confirmDelete")});

        } else if("cut".equals(action))
          cutedPath = bookmarkPath;
        else if("paste".equals(action) && cutedPath != null) {

          bookmarkManager.moveBookmark(cutedPath, bookmarkPath);
          bookmarkManager.storeBookmarks();
          cutedPath = null;

        } else if("edit".equals(action) || "addItem".equals(action) || "addCat".equals(action) || "share".equals(action)) {
          boolean isNew = "addItem".equals(action) || "addCat".equals(action);
          String header;
          if("edit".equals(action))
            header = NodeL10n.getBase().getString("BookmarkEditorToadlet.edit" + ((bookmark instanceof BookmarkItem) ? "Bookmark" : "Category") + "Title");
          else if("addItem".equals(action))
            header = NodeL10n.getBase().getString("BookmarkEditorToadlet.addNewBookmark");
          else if("share".equals(action))
            header = NodeL10n.getBase().getString("BookmarkEditorToadlet.share");
          else
            header = NodeL10n.getBase().getString("BookmarkEditorToadlet.addNewCategory");

          HTMLNode actionBoxContent = pageMaker.getInfobox("infobox-query", header, content, "bookmark-action", false);

          HTMLNode form = ctx.addFormChild(actionBoxContent, "", "editBookmarkForm");

          form.addChild("label", "for", "name", (NodeL10n.getBase().getString("BookmarkEditorToadlet.nameLabel") + ' '));
          form.addChild("input", new String[]{"type", "id", "name", "size", "value"}, new String[]{"text", "name", "name", "20", !isNew ? bookmark.getVisibleName() : ""});

          form.addChild("br");
          if(("edit".equals(action) && bookmark instanceof BookmarkItem) || "addItem".equals(action) || "share".equals(action)) {
            BookmarkItem item = isNew ? null : (BookmarkItem) bookmark;
            String key = !isNew ? item.getKey() : "";
            form.addChild("label", "for", "key", (NodeL10n.getBase().getString("BookmarkEditorToadlet.keyLabel") + ' '));
            form.addChild("input", new String[] {"type", "id", "name", "size", "value"}, new String[] {"text", "key", "key", "50", key});
            form.addChild("br");
            if("edit".equals(action) || "addItem".equals(action)) {
              form.addChild("label", "for", "descB", (NodeL10n.getBase().getString("BookmarkEditorToadlet.descLabel") + ' '));
              form.addChild("br");
              form.addChild("textarea", new String[]{"id", "name", "row", "cols"}, new String[]{"descB", "descB", "3", "70"}, (isNew ? "" : item.getDescription()));
              form.addChild("br");
              form.addChild("label", "for", "descB", (NodeL10n.getBase().getString("BookmarkEditorToadlet.explainLabel") + ' '));
              form.addChild("br");
              form.addChild("textarea", new String[]{"id", "name", "row", "cols"}, new String[]{"explain", "explain", "3", "70"}, (isNew ? "" : item.getShortDescription()));
              form.addChild("br");
            }
            form.addChild("label", "for", "hasAnActivelink", (NodeL10n.getBase().getString("BookmarkEditorToadlet.hasAnActivelinkLabel") + ' '));
            if(!isNew && item.hasAnActivelink())
              form.addChild("input", new String[]{"type", "id", "name", "checked"}, new String[]{"checkbox", "hasAnActivelink", "hasAnActivelink", String.valueOf(item.hasAnActivelink())});
            else
              form.addChild("input", new String[]{"type", "id", "name"}, new String[]{"checkbox", "hasAnActivelink", "hasAnActivelink"});
            if(core.node.getDarknetConnections().length > 0 && ("addItem".equals(action) || "share".equals(action))) {
              form.addChild("br");
              form.addChild("br");
              HTMLNode peerTable = form.addChild("table", "class", "darknet_connections");
              peerTable.addChild("th", "colspan", "2", NodeL10n.getBase().getString("QueueToadlet.recommendToFriends"));
              for(DarknetPeerNode peer : core.node.getDarknetConnections()) {
                HTMLNode peerRow = peerTable.addChild("tr", "class", "darknet_connections_normal");
                peerRow.addChild("td", "class", "peer-marker").addChild("input", new String[] { "type", "name" }, new String[] { "checkbox", "node_" + peer.hashCode() });
                peerRow.addChild("td", "class", "peer-name").addChild("#", peer.getName());
              }
              form.addChild("label", "for", "descB", (NodeL10n.getBase().getString("BookmarkEditorToadlet.publicDescLabel") + ' '));
              form.addChild("br");
              form.addChild("textarea", new String[]{"id", "name", "row", "cols"}, new String[]{"descB", "publicDescB", "3", "70"}, (isNew ? "" : item.getDescription()));
              form.addChild("br");
            }
          }

          form.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "bookmark", bookmarkPath});

          form.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "action", req.getParam("action")});

          form.addChild("input", new String[]{"type", "value"}, new String[]{"submit", "share".equals(action) ? NodeL10n.getBase().getString("BookmarkEditorToadlet.share") : NodeL10n.getBase().getString("BookmarkEditorToadlet.save")});
        } else if("up".equals(action))
          bookmarkManager.moveBookmarkUp(bookmarkPath, true);
        else if("down".equals(action))
          bookmarkManager.moveBookmarkDown(bookmarkPath, true);
    }

    if(cutedPath != null) {
      HTMLNode infoBoxContent =
        pageMaker.getInfobox("infobox-normal", NodeL10n.getBase().getString("BookmarkEditorToadlet.pasteTitle"), content, null, false);
      infoBoxContent.addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.pasteOrCancel"));
      HTMLNode cancelForm = ctx.addFormChild(infoBoxContent, "/bookmarkEditor/", "cancelCutForm");
      cancelForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "cancelCut", NodeL10n.getBase().getString("BookmarkEditorToadlet.cancelCut")});
      cancelForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"hidden", "action", "cancelCut"});
    }

    pageMaker.getInfobox("infobox-normal", NodeL10n.getBase().getString("BookmarkEditorToadlet.myBookmarksTitle"), content, "bookmark-title", false).
      addChild(getBookmarksList(bookmarkManager));

    HTMLNode addDefaultBookmarksForm = ctx.addFormChild(content, "", "AddDefaultBookmarks");
    addDefaultBookmarksForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "AddDefaultBookmarks", NodeL10n.getBase().getString("BookmarkEditorToadlet.addDefaultBookmarks")});

    if(logDEBUG)
      Logger.debug(this, "Returning:\n"+pageNode.generate());
   
    this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
View Full Code Here

  public void handleMethodPOST(URI uri, HTTPRequest req, ToadletContext ctx)
    throws ToadletContextClosedException, IOException {
    PageMaker pageMaker = ctx.getPageMaker();
    BookmarkManager bookmarkManager = ctx.getBookmarkManager();
    PageNode page = pageMaker.getPageNode(NodeL10n.getBase().getString("BookmarkEditorToadlet.title"), ctx);
    HTMLNode pageNode = page.outer;
    HTMLNode content = page.content;

    if(req.isPartSet("AddDefaultBookmarks")) {
      bookmarkManager.reAddDefaultBookmarks();
      this.writeTemporaryRedirect(ctx, "Ok", "/");
      return;
    }

    String bookmarkPath = req.getPartAsStringFailsafe("bookmark", MAX_BOOKMARK_PATH_LENGTH);
    try {

      Bookmark bookmark;
      if(bookmarkPath.endsWith("/"))
        bookmark = bookmarkManager.getCategoryByPath(bookmarkPath);
      else
        bookmark = bookmarkManager.getItemByPath(bookmarkPath);
      if(bookmark == null && !req.isPartSet("cancelCut")) {
        pageMaker.getInfobox("infobox-error", NodeL10n.getBase().getString("BookmarkEditorToadlet.error"), content, "bookmark-error", false).
          addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.bookmarkDoesNotExist", new String[]{"bookmark"}, new String[]{bookmarkPath}));
        this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      }


      String action = req.getPartAsStringFailsafe("action", MAX_ACTION_LENGTH);

      if(req.isPartSet("confirmdelete")) {
        bookmarkManager.removeBookmark(bookmarkPath);
        bookmarkManager.storeBookmarks();
        pageMaker.getInfobox("infobox-success", NodeL10n.getBase().getString("BookmarkEditorToadlet.deleteSucceededTitle"), content, "bookmark-successful-delete", false).
          addChild("p", NodeL10n.getBase().getString("BookmarkEditorToadlet.deleteSucceeded"));

      } else if(req.isPartSet("cancelCut"))
        cutedPath = null;
      else if("edit".equals(action) || "addItem".equals(action) || "addCat".equals(action)) {

        String name = "unnamed";
        if(req.isPartSet("name"))
          name = req.getPartAsStringFailsafe("name", MAX_NAME_LENGTH);

        if("edit".equals(action)) {
          bookmarkManager.renameBookmark(bookmarkPath, name);
          boolean hasAnActivelink = req.isPartSet("hasAnActivelink");
          if(bookmark instanceof BookmarkItem) {
            BookmarkItem item = (BookmarkItem) bookmark;
            item.update(new FreenetURI(req.getPartAsStringFailsafe("key", MAX_KEY_LENGTH)), hasAnActivelink, req.getPartAsStringFailsafe("descB", MAX_KEY_LENGTH), req.getPartAsStringFailsafe("explain", MAX_EXPLANATION_LENGTH));
            sendBookmarkFeeds(req, item, req.getPartAsStringFailsafe("publicDescB", MAX_KEY_LENGTH));
          }
          bookmarkManager.storeBookmarks();

          pageMaker.getInfobox("infobox-success", NodeL10n.getBase().getString("BookmarkEditorToadlet.changesSavedTitle"), content, "bookmark-error", false).
            addChild("p", NodeL10n.getBase().getString("BookmarkEditorToadlet.changesSaved"));

        } else if("addItem".equals(action) || "addCat".equals(action)) {

          Bookmark newBookmark = null;
          if("addItem".equals(action)) {
            FreenetURI key = new FreenetURI(req.getPartAsStringFailsafe("key", MAX_KEY_LENGTH));
            /* TODO:
             * <nextgens> I suggest you implement a HTTPRequest.getBoolean(String name) using Fields.stringtobool
             * <nextgens> HTTPRequest.getBoolean(String name, boolean default) even
             *
             * - values as "on", "true", "yes" should be accepted.
             */
            boolean hasAnActivelink = req.isPartSet("hasAnActivelink");
            if (name.contains("/")) {
              pageMaker.getInfobox("infobox-error", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidNameTitle"), content, "bookmark-error", false).
                addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidName"));
            } else
              newBookmark = new BookmarkItem(key, name, req.getPartAsStringFailsafe("descB", MAX_KEY_LENGTH), req.getPartAsStringFailsafe("explain", MAX_EXPLANATION_LENGTH), hasAnActivelink, ctx.getAlertManager());
          } else
            if (name.contains("/")) {
              pageMaker.getInfobox("infobox-error", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidNameTitle"), content, "bookmark-error", false).
                addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidName"));
            } else
              newBookmark = new BookmarkCategory(name);
         
          if (newBookmark != null) {

            bookmarkManager.addBookmark(bookmarkPath, newBookmark);
            bookmarkManager.storeBookmarks();
            if(newBookmark instanceof BookmarkItem)
              sendBookmarkFeeds(req, (BookmarkItem) newBookmark, req.getPartAsStringFailsafe("publicDescB", MAX_KEY_LENGTH));

            pageMaker.getInfobox("infobox-success", NodeL10n.getBase().getString("BookmarkEditorToadlet.addedNewBookmarkTitle"), content, "bookmark-add-new", false).
              addChild("p", NodeL10n.getBase().getString("BookmarkEditorToadlet.addedNewBookmark"));
          }
        }
      }
      else if("share".equals(action))
        sendBookmarkFeeds(req, (BookmarkItem) bookmark, req.getPartAsStringFailsafe("publicDescB", MAX_KEY_LENGTH));
    } catch(MalformedURLException mue) {
      pageMaker.getInfobox("infobox-error", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidKeyTitle"), content, "bookmark-error", false).
        addChild("#", NodeL10n.getBase().getString("BookmarkEditorToadlet.invalidKey"));
    }
    pageMaker.getInfobox("infobox-normal", NodeL10n.getBase().getString("BookmarkEditorToadlet.myBookmarksTitle"), content, "bookmarks", false).
      addChild(getBookmarksList(bookmarkManager));
   
    HTMLNode addDefaultBookmarksForm = ctx.addFormChild(content, "", "AddDefaultBookmarks");
    addDefaultBookmarksForm.addChild("input", new String[]{"type", "name", "value"}, new String[]{"submit", "AddDefaultBookmarks", NodeL10n.getBase().getString("BookmarkEditorToadlet.addDefaultBookmarks")});

    this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
  }
View Full Code Here

      return NodeL10n.getBase().getString("UserAlert.hide");
    }

    @Override
    public HTMLNode getHTMLText() {
      return new HTMLNode("#", getText());
    }
View Full Code Here

      }

      if(request.isPartSet("delete_request") && (request.getPartAsStringFailsafe("delete_request", 128).length() > 0)) {
        // Confirm box
        PageNode page = ctx.getPageMaker().getPageNode(l10n("confirmDeleteTitle"), ctx);
        HTMLNode inner = page.content;
        HTMLNode content = ctx.getPageMaker().getInfobox("infobox-warning", l10n("confirmDeleteTitle"), inner, "confirm-delete-title", true);
       
        HTMLNode deleteNode = new HTMLNode("p");
        HTMLNode deleteForm = ctx.addFormChild(deleteNode, path(), "queueDeleteForm");
        HTMLNode infoList = deleteForm.addChild("ul");
       
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          part = part.substring("identifier-".length());
          if(part.length() > 50) continue; // It's just a number
         
          String identifier = request.getPartAsStringFailsafe("identifier-"+part, MAX_IDENTIFIER_LENGTH);
          if(identifier == null) continue;
          String filename = request.getPartAsStringFailsafe("filename-"+part, MAX_FILENAME_LENGTH);
          String keyString = request.getPartAsStringFailsafe("key-"+part, MAX_KEY_LENGTH);
          String type = request.getPartAsStringFailsafe("type-"+part, MAX_TYPE_LENGTH);
          String size = request.getPartAsStringFailsafe("size-"+part, 50);
          if(filename != null) {
            HTMLNode line = infoList.addChild("li");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet.filenameLabel")+" ");
            if(keyString != null) {
              line.addChild("a", "href", "/"+keyString, filename);
            } else {
              line.addChild("#", filename);
            }
          }
          if(type != null && !type.equals("")) {
            HTMLNode line = infoList.addChild("li");
            boolean finalized = request.isPartSet("finalizedType");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet."+(finalized ? "mimeType" : "expectedMimeType"), new String[] { "mime" }, new String[] { type }));
          }
          if(size != null) {
            HTMLNode line = infoList.addChild("li");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet.sizeLabel") + " " + size);
          }
          infoList.addChild("#", l10n("deleteFileFromTemp"));
          infoList.addChild("input", new String[] { "type", "name", "value", "checked" },
                  new String[] { "checkbox", "identifier-"+part, identifier, "checked" });
        }
       
        content.addChild("p", l10n("confirmDelete"));
        content.addChild(deleteNode);

        deleteForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "submit", "remove_request", NodeL10n.getBase().getString("Toadlet.yes") });
        deleteForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "submit", "cancel", NodeL10n.getBase().getString("Toadlet.no") });

        this.writeHTMLReply(ctx, 200, "OK", page.outer.generate());
        return;
      } else if(request.isPartSet("remove_request") && (request.getPartAsStringFailsafe("remove_request", 128).length() > 0)) {
       
        // FIXME optimise into a single database job.
       
        String identifier = "";
        try {
          for(String part : request.getParts()) {
            if(!part.startsWith("identifier-")) continue;
            identifier = part.substring("identifier-".length());
            if(identifier.length() > 50) continue;
            identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
            if(logMINOR) Logger.minor(this, "Removing "+identifier);
            fcp.removeGlobalRequestBlocking(identifier);
          }
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("remove_finished_uploads_request") && (request.getPartAsStringFailsafe("remove_finished_uploads_request", 128).length() > 0)) {
        String identifier = "";
        try {
          RequestStatus[] reqs;
          reqs = fcp.getGlobalRequests();
                                        for(RequestStatus r : reqs) {
            if(r instanceof UploadFileRequestStatus) {
              UploadFileRequestStatus upload = (UploadFileRequestStatus)r;
              if(upload.hasSucceeded()) {
                identifier = upload.getIdentifier();
                fcp.removeGlobalRequestBlocking(identifier);
              }
            }
          } 
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
       
      } else if(request.isPartSet("remove_finished_downloads_request") && (request.getPartAsStringFailsafe("remove_finished_downloads_request", 128).length() > 0)) {
        String identifier = "";
        try {
          RequestStatus[] reqs;
          reqs = fcp.getGlobalRequests();
         
          boolean hasIdentifier = false;
          for(String part : request.getParts()) {
            if(!part.startsWith("identifier-")) continue;
            hasIdentifier = true;
            identifier = part.substring("identifier-".length());
            if(identifier.length() > 50) continue;
            identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
            if(logMINOR) Logger.minor(this, "Removing "+identifier);
            fcp.removeGlobalRequestBlocking(identifier);
          }
         
          if(!hasIdentifier) { // delete all, because no identifier is given
            for(RequestStatus r : reqs) {
              if(r instanceof DownloadRequestStatus) {
                DownloadRequestStatus download = (DownloadRequestStatus)r;
                if(download.isPersistent() && download.hasSucceeded() && download.isTotalFinalized() && !download.toTempSpace()) {
                  identifier = download.getIdentifier();
                  fcp.removeGlobalRequestBlocking(identifier);
                }
              }
            }
          }
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      }
      else if(request.isPartSet("restart_request") && (request.getPartAsStringFailsafe("restart_request", 128).length() > 0)) {
        boolean disableFilterData = request.isPartSet("disableFilterData");
       
       
        String identifier = "";
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          identifier = part.substring("identifier-".length());
          if(identifier.length() > 50) continue;
          identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
          if(logMINOR) Logger.minor(this, "Restarting "+identifier);
          try {
            fcp.restartBlocking(identifier, disableFilterData);
          } catch (PersistenceDisabledException e) {
            sendPersistenceDisabledError(ctx);
            return;
          }
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("panic") && (request.getPartAsStringFailsafe("panic", 128).length() > 0)) {
        if(SimpleToadletServer.noConfirmPanic) {
          core.node.killMasterKeysFile();
          core.node.panic();
          sendPanicingPage(ctx);
          core.node.finishPanic();
          return;
        } else {
          sendConfirmPanicPage(ctx);
          return;
        }
      } else if(request.isPartSet("confirmpanic") && (request.getPartAsStringFailsafe("confirmpanic", 128).length() > 0)) {
        core.node.killMasterKeysFile();
        core.node.panic();
        sendPanicingPage(ctx);
        core.node.finishPanic();
        return;
      } else if(request.isPartSet("download")) {
        // Queue a download
        if(!request.isPartSet("key")) {
          writeError(l10n("errorNoKey"), l10n("errorNoKeyToD"), ctx);
          return;
        }
        String expectedMIMEType = null;
        if(request.isPartSet("type")) {
          expectedMIMEType = request.getPartAsStringFailsafe("type", MAX_TYPE_LENGTH);
        }
        FreenetURI fetchURI;
        try {
          fetchURI = new FreenetURI(request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH));
        } catch (MalformedURLException e) {
          writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToD"), ctx);
          return;
        }
        String persistence = request.getPartAsStringFailsafe("persistence", 32);
        String returnType = request.getPartAsStringFailsafe("return-type", 32);
        boolean filterData = request.isPartSet("filterData");
        String downloadPath;
        File downloadsDir = null;
        //Download to disk disabled and initialized.
        if (request.isPartSet("path") && !core.isDownloadDisabled()) {
          downloadPath = request.getPartAsStringFailsafe("path", MAX_FILENAME_LENGTH);
          try {
            downloadsDir = getDownloadsDir(downloadPath);
          } catch (NotAllowedException e) {
            downloadDisallowedPage(e, downloadPath, ctx);
            return;
          }
        //Downloading to disk not initialized and/or disabled.
        } else returnType = "direct";
        try {
          fcp.makePersistentGlobalRequestBlocking(fetchURI, filterData, expectedMIMEType, persistence, returnType, false, downloadsDir);
        } catch (NotAllowedException e) {
          this.writeError(l10n("errorDToDisk"), l10n("errorDToDiskConfig"), ctx);
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("bulkDownloads")) {
        String bulkDownloadsAsString = request.getPartAsStringFailsafe("bulkDownloads", 262144);
        String[] keys = bulkDownloadsAsString.split("\n");
        if(("".equals(bulkDownloadsAsString)) || (keys.length < 1)) {
          writePermanentRedirect(ctx, "Done", path());
          return;
        }
        LinkedList<String> success = new LinkedList<String>(), failure = new LinkedList<String>();
        boolean filterData = request.isPartSet("filterData");
        String target = request.getPartAsStringFailsafe("target", 128);
        if(target == null) target = "direct";
        String downloadPath;
        File downloadsDir = null;
        if (request.isPartSet("path") && !core.isDownloadDisabled()) {
          downloadPath = request.getPartAsStringFailsafe("path", MAX_FILENAME_LENGTH);
          try {
            downloadsDir = getDownloadsDir(downloadPath);
          } catch (NotAllowedException e) {
            downloadDisallowedPage(e, downloadPath, ctx);
            return;
          }
        } else target = "direct";

        for(int i=0; i<keys.length; i++) {
          String currentKey = keys[i];

          // trim leading/trailing space
          currentKey = currentKey.trim();
          if (currentKey.length() == 0)
            continue;

          try {
            FreenetURI fetchURI = new FreenetURI(currentKey);
            fcp.makePersistentGlobalRequestBlocking(fetchURI, filterData, null,
                    "forever", target, false, downloadsDir);
            success.add(fetchURI.toString(true, false));
          } catch (Exception e) {
            failure.add(currentKey);
            Logger.error(this,
                    "An error occured while attempting to download key("+i+") : "+
                    currentKey+ " : "+e.getMessage());
          }
        }

        boolean displayFailureBox = failure.size() > 0;
        boolean displaySuccessBox = success.size() > 0;

        PageNode page = ctx.getPageMaker().getPageNode(l10n("downloadFiles"), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;

        HTMLNode alertContent = ctx.getPageMaker().getInfobox(
                (displayFailureBox ? "infobox-warning" : "infobox-info"),
                l10n("downloadFiles"), contentNode, "grouped-downloads", true);
        if(displaySuccessBox) {
          HTMLNode successDiv = alertContent.addChild("ul");
          successDiv.addChild("#", l10n("enqueuedSuccessfully", "number",
                  String.valueOf(success.size())));
          for(String s: success) {
            HTMLNode line = successDiv.addChild("li");
            line.addChild("#", s);
          }
          successDiv.addChild("br");
        }
        if(displayFailureBox) {
          HTMLNode failureDiv = alertContent.addChild("ul");
          if(displayFailureBox) {
            failureDiv.addChild("#", l10n("enqueuedFailure", "number",
                    String.valueOf(failure.size())));
            for(String f: failure) {
              HTMLNode line = failureDiv.addChild("li");
              line.addChild("#", f);
            }
          }
          failureDiv.addChild("br");
        }
        alertContent.addChild("a", "href", path(),
                NodeL10n.getBase().getString("Toadlet.returnToQueuepage"));
        writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      } else if (request.isPartSet("change_priority_top")) {
        handleChangePriority(request, ctx, "_top");
        return;
      } else if (request.isPartSet("change_priority_bottom")) {
        handleChangePriority(request, ctx, "_bottom");
        return;
        // FIXME factor out the next 3 items, they are very messy!
      } else if (request.getPartAsStringFailsafe("insert", 128).length() > 0) {
        final FreenetURI insertURI;
        String keyType = request.getPartAsStringFailsafe("keytype", 10);
        if ("CHK".equals(keyType)) {
          insertURI = new FreenetURI("CHK@");
          if(fiw != null)
            fiw.reportCanonicalInsert();
        } else if("SSK".equals(keyType)) {
          insertURI = new FreenetURI("SSK@");
          if(fiw != null)
            fiw.reportRandomInsert();
        } else if("specify".equals(keyType)) {
          try {
            String u = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
            insertURI = new FreenetURI(u);
            if(logMINOR)
              Logger.minor(this, "Inserting key: "+insertURI+" ("+u+")");
          } catch (MalformedURLException mue1) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx, false, true);
            return;
          }
        } else {
          writeError(l10n("errorMustSpecifyKeyTypeTitle"),
                     l10n("errorMustSpecifyKeyType"), ctx, false, true);
          return;
        }
        final HTTPUploadedFile file = request.getUploadedFile("filename");
        if (file == null || file.getFilename().trim().length() == 0) {
          writeError(l10n("errorNoFileSelected"), l10n("errorNoFileSelectedU"), ctx, false, true);
          return;
        }
        final boolean compress = request.getPartAsStringFailsafe("compress", 128).length() > 0;
        final String identifier = file.getFilename() + "-fred-" + System.currentTimeMillis();
        final String compatibilityMode = request.getPartAsStringFailsafe("compatibilityMode", 100);
        final CompatibilityMode cmode;
        if(compatibilityMode.equals(""))
          cmode = CompatibilityMode.COMPAT_DEFAULT.intern();
        else
          cmode = CompatibilityMode.valueOf(compatibilityMode).intern();
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        final String fnam;
        if(insertURI.getKeyType().equals("CHK") || keyType.equals("SSK"))
          fnam = file.getFilename();
        else
          fnam = null;
        /* copy bucket data */
        final RandomAccessBucket copiedBucket = core.persistentTempBucketFactory.makeBucket(file.getData().size());
        BucketTools.copy(file.getData(), copiedBucket);
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              try {
              final ClientPut clientPut;
              try {
                clientPut = new ClientPut(fcp.getGlobalForeverClient(), insertURI, identifier, Integer.MAX_VALUE, null, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, UploadFrom.DIRECT, null, file.getContentType(), copiedBucket, null, fnam, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, cmode, overrideSplitfileKey, false, fcp.core);
                if(clientPut != null)
                  try {
                    fcp.startBlocking(clientPut, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same file twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (NotAllowedException e) {
                writeError(l10n("errorAccessDenied"), l10n("errorAccessDeniedFile", "file", file.getFilename()), ctx, false, true);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", file.getFilename()), ctx, false, true);
                return false;
              } catch (MalformedURLException mue1) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx, false, true);
                return false;
              } catch (MetadataUnresolvedException e) {
                Logger.error(this, "Unresolved metadata in starting insert from data uploaded from browser: "+e, e);
                writePermanentRedirect(ctx, "Done", path());
                return false;
                // FIXME should this be a proper localised message? It shouldn't happen... but we'd like to get reports if it does.
              } catch (Throwable t) {
                writeInternalError(t, ctx);
                return false;
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet(LocalFileBrowserToadlet.selectFile)) {
        final String filename = request.getPartAsStringFailsafe("filename", MAX_FILENAME_LENGTH);
        if(logMINOR) Logger.minor(this, "Inserting local file: "+filename);
        final File file = new File(filename);
        final String identifier = file.getName() + "-fred-" + System.currentTimeMillis();
        final String contentType = DefaultMIMETypes.guessMIMEType(filename, false);
        final FreenetURI furi;
        final String key = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
        final boolean compress = request.isPartSet("compress");
        final String compatibilityMode = request.getPartAsStringFailsafe("compatibilityMode", 100);
        final CompatibilityMode cmode;
        if(compatibilityMode.equals(""))
          cmode = CompatibilityMode.COMPAT_DEFAULT;
        else
          cmode = CompatibilityMode.valueOf(compatibilityMode);
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        if(key != null) {
          try {
            furi = new FreenetURI(key);
          } catch (MalformedURLException e) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
            return;
          }
        } else {
          furi = new FreenetURI("CHK@");
        }
        final String target;
        if(furi.getDocName() != null)
          target = null;
        else
          target = file.getName();
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartLocalFileInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              final ClientPut clientPut;
              try {
              try {
                clientPut = new ClientPut(fcp.getGlobalForeverClient(), furi, identifier, Integer.MAX_VALUE, null, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, UploadFrom.DISK, file, contentType, new FileBucket(file, true, false, false, false), null, target, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, cmode, overrideSplitfileKey, false, fcp.core);
                if(logMINOR) Logger.minor(this, "Started global request to insert "+file+" to CHK@ as "+identifier);
                if(clientPut != null)
                  try {
                    fcp.startBlocking(clientPut, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  } catch (PersistenceDisabledException e) {
                    // Impossible???
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same file twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (MalformedURLException e) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", target), ctx);
                return false;
              } catch (NotAllowedException e) {
                writeError(l10n("errorAccessDenied"), l10n("errorAccessDeniedFile", new String[]{ "file" }, new String[]{ file.getName() }), ctx);
                return false;
              } catch (MetadataUnresolvedException e) {
                Logger.error(this, "Unresolved metadata in starting insert from data from file: "+e, e);
                writePermanentRedirect(ctx, "Done", path());
                return false;
                // FIXME should this be a proper localised message? It shouldn't happen... but we'd like to get reports if it does.
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet(LocalFileBrowserToadlet.selectDir)) {
        final String filename = request.getPartAsStringFailsafe("filename", MAX_FILENAME_LENGTH);
        if(logMINOR) Logger.minor(this, "Inserting local directory: "+filename);
        final File file = new File(filename);
        final String identifier = file.getName() + "-fred-" + System.currentTimeMillis();
        final FreenetURI furi;
        final String key = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
        final boolean compress = request.isPartSet("compress");
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        if(key != null) {
          try {
            furi = new FreenetURI(key);
          } catch (MalformedURLException e) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
            return;
          }
        } else {
          furi = new FreenetURI("CHK@");
        }
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartLocalDirInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              ClientPutDir clientPutDir;
              try {
              try {
                clientPutDir = new ClientPutDir(fcp.getGlobalForeverClient(), furi, identifier, Integer.MAX_VALUE, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, file, null, false, /* make include hidden files configurable? FIXME */ false, true, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, overrideSplitfileKey, fcp.core);
                if(logMINOR) Logger.minor(this, "Started global request to insert dir "+file+" to "+furi+" as "+identifier);
                if(clientPutDir != null)
                  try {
                    fcp.startBlocking(clientPutDir, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  } catch (PersistenceDisabledException e) {
                    sendPersistenceDisabledError(ctx);
                    return false;
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same directory twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (MalformedURLException e) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", file.toString()), ctx);
                return false;
              } catch (TooManyFilesInsertException e) {
                writeError(l10n("tooManyFilesInOneFolder"), l10n("tooManyFilesInOneFolder"), ctx);
                return false;
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet("recommend_request")) {
        PageNode page = ctx.getPageMaker().getPageNode(l10n("recommendAFileToFriends"), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;
        HTMLNode infoboxContent = ctx.getPageMaker().getInfobox("#", l10n("recommendAFileToFriends"), contentNode, "recommend-file", true);
        HTMLNode form = ctx.addFormChild(infoboxContent, path(), "recommendForm2");
       
        int x = 0;
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          String key = request.getPartAsStringFailsafe("key-"+part.substring("identifier-".length()), MAX_KEY_LENGTH);
          if(key == null || key.equals("")) continue;
          form.addChild("#", l10n("key") + ":");
          form.addChild("br");
          form.addChild("#", key);
          form.addChild("br");
          form.addChild("input", new String[] { "type", "name", "value" },
              new String[] { "hidden", "key-"+x, key });
        }
        form.addChild("label", "for", "descB", (l10n("recommendDescription") + ' '));
        form.addChild("br");
        form.addChild("textarea",
                new String[]{"id", "name", "row", "cols"},
                new String[]{"descB", "description", "3", "70"});
        form.addChild("br");

        HTMLNode peerTable = form.addChild("table", "class", "darknet_connections");
        peerTable.addChild("th", "colspan", "2", l10n("recommendToFriends"));
        for(DarknetPeerNode peer : core.node.getDarknetConnections()) {
          HTMLNode peerRow = peerTable.addChild("tr", "class", "darknet_connections_normal");
          peerRow.addChild("td", "class", "peer-marker").addChild("input",
                  new String[] { "type", "name" },
                  new String[] { "checkbox", "node_" + peer.hashCode() });
          peerRow.addChild("td", "class", "peer-name").addChild("#", peer.getName());
        }

        form.addChild("input",
                new String[]{"type", "name", "value"},
                new String[]{"submit", "recommend_uri", l10n("recommend")});
View Full Code Here

    if(!(isFailed || isCompleted))
      form.addChild(createPriorityControl(pageMaker, ctx, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, priorityClasses, advancedModeEnabled, isUpload, top ? "_top" : "_bottom"));
  }

  private HTMLNode createCheckboxCell(RequestStatus clientRequest, int counter) {
    HTMLNode cell = new HTMLNode("td", "class", "checkbox-cell");
    String identifier = clientRequest.getIdentifier();
    cell.addChild("input", new String[] { "type", "name", "value" },
        new String[] { "checkbox", "identifier-"+counter, identifier } );
    FreenetURI uri;
    long size = -1;
    String filename = null;
    if(clientRequest instanceof DownloadRequestStatus) {
      uri = clientRequest.getURI();
      size = clientRequest.getDataSize();
    } else if(clientRequest instanceof UploadRequestStatus) {
      uri = ((UploadRequestStatus)clientRequest).getFinalURI();
      size = clientRequest.getDataSize();
    } else {
      uri = null;
    }
    if(uri != null) {
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "key-"+counter, uri.toASCIIString() });
    }
    filename = clientRequest.getPreferredFilenameSafe();
    if(size != -1)
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "size-"+counter, Long.toString(size) });
    if(filename != null)
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "filename-"+counter, filename });
    return cell;
  }
View Full Code Here

TOP

Related Classes of freenet.support.HTMLNode

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.