adobe-indesignextendscriptbasil.js

Basil.js Check URL before pasting image?


I want to eventually make a folder on my server that will be filled with images, using basil.js I would like to extract them and place them into indesign.

The script works but I need like an IF statement that will error check if the URL actually exists... because currently it will place a black place holder even if there is no actually image at that URL..

if != url ..... so I wouldn't have to use a FOR loop ...and I would keep adding the images until the whole directory is checked.

There is probably not how you do this... sorry but as I am a novice I keep making a patch job of it.

#includepath "~/Documents/;%USERPROFILE%Documents";
#include "basiljs/bundle/basil.js";

var count = 1;
var x = 100;
var y = 100;

function draw() {

    for (i = 0; i < 15; i++) {

   var url = "http://www.minceandcheesepie.com/spaceinvaders/image" +  count + ".png";

   var newFile = new File("~/Documents/basiljs/user/data/image" + count + ".png");

  b.download(url, newFile);
  b.image('image' + count +'.png', x, y);

    x += 200; 
    y += 200;
    count++;

    app.select(NothingEnum.nothing, undefined);
    }

}
b.go();

Solution

  • You need to make an HTTP HEAD request to check what's the result of the URL:

    reply = "";
    conn = new Socket;
    
    if (conn.open ("www.minceandcheesepie.com:80")) {
        // send a HTTP HEAD request
        conn.writeln("HEAD /spaceinvaders/image" + counter + ".png HTTP/1.0\r\nConnection: close\r\nHost: www.minceandcheesepie.com\r\n\r\n");
        // and read the server's reply
        reply = conn.read(999999);
        conn.close();
    }
    

    Then in the reply you get a string from the server(server response) which tells you if the page exists, then you just need to parse it by the result of the page(if it's 200-the page exists):

    var serverStatusCode = parseInt(reply.split('\n\n')[0].split('\n')[0].split(' ')[1]);
    if (serverStatusCode === 200) {
        alert('exists');
    } else {
        alert('not exists');
    }
    

    Server response example for URL exists:

    HTTP/1.1 200 OK
    Date: Wed, 16 Dec 2015 06:37:20 GMT
    Server: Apache
    Last-Modified: Wed, 16 Dec 2015 02:41:08 GMT
    ETag: "67d-526fad6ab0af2"
    Accept-Ranges: bytes
    Content-Length: 1661
    Connection: close
    Content-Type: image/png
    

    Server response example for non exists URL:

    HTTP/1.1 404 Not Found
    Date: Wed, 16 Dec 2015 06:47:33 GMT
    Server: Apache
    Vary: Accept-Encoding
    Connection: close
    Content-Type: text/html; charset=iso-8859-1