Panopticonize

API Documentation

Basic Use

Download Source

Usage


class Test
{
		
 public static void main(String[] args)
 {
	  Panopticonize panopticon = new Panopticonize("--api key here--");
	  Panopticonize.File f = panopticon.UploadForProcessing("-- file here --");
	  f.AddListener(new Panopticonize.IFileEventsListener() {
		
		@Override
		public void OnUploadProgressChanged(int i) {
			// TODO Auto-generated method stub
			 System.out.println("Upload: " + i);
		}
		
		@Override
		public void OnStatusChanged(Panopticonize.FileStatus i) {
			// TODO Auto-generated method stub
			System.out.println("Status: " + i);
		}
		
		@Override
		public void OnProcessProgressChanged(int i) {
			// TODO Auto-generated method stub
			System.out.println("Progress: " + i);
		}
		
		@Override
		public void OnPlaceInQueueChanged(int i, int l) {
			// TODO Auto-generated method stub
			System.out.println("In Queue: " + i + " of " + l);
		}

		
	});
	  
	  System.out.println("Uploading");
	  while (true)
	  {
		 try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
 }
}
	

Code


	  import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

public class Panopticonize {
	public enum FileStatus {
		UPLOADING, INQUEUE, PROCESSING, DOWNLOADING, DONE
	};

	public final static String SERVER = "http://panopticonize.com/";
	private String APIKey;
	
	public String getAPIKey() {
		return APIKey;
	}

	public Panopticonize(String apikey) {
		APIKey = apikey;
	}

	public File UploadForProcessing(String filename, String destination) {
		Panopticonize.File f = new Panopticonize.File(filename, destination);
		f.Upload(APIKey);
		return f;
	}

	public File UploadForProcessing(String filename) {
		return UploadForProcessing(filename, filename + ".panop.mp4");
	}

	public interface IFileEventsListener {
		void OnProcessProgressChanged(int i);
		void OnUploadProgressChanged(int i);
		void OnStatusChanged(FileStatus i);
		void OnPlaceInQueueChanged(int i, int l);
	}

	private class Uploader extends Thread {
		File f;

		public Uploader(File f) {
			this.f = f;
		}

		@Override
		public void run() {
			super.run();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Panopticonize.SERVER
					+ "/api.php?key=" + f.apikey + "&a=upload");
			FileBody bin = new FileBody(new java.io.File(f.LocalFilename));
			MultipartEntityWithProgressBar reqEntity = new MultipartEntityWithProgressBar(
					new Panopticonize.UploadListener(bin.getContentLength(), f));
			reqEntity.addPart("files", bin);
			httppost.setEntity(reqEntity);
			try {
				HttpResponse uploadResponse = httpClient.execute(httppost);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(uploadResponse.getEntity()
								.getContent()));
				String ss = null;
				String tt = "";
				while ((ss = reader.readLine()) != null)
					tt += ss;

				Hashtable ht = f.gson.fromJson(tt, Hashtable.class);
				if (ht.containsKey("code")) {
					throw new PanopticonizeException(Integer.parseInt(ht.get(
							"code").toString()), ht.get("details").toString());
				}
				// if its not an error, then process...
				f.servername = ht.get("id").toString();
				// when upload complete
				f.Status = FileStatus.INQUEUE;
				f.StartGetProgress();

			} catch (Exception e) {
				// do nothing
			}

		}

	}

	public class File {
		private IFileEventsListener list;
		private int Progress = 0;
		private FileStatus Status = FileStatus.UPLOADING;
		private int PlaceInQueue = 0;
		private int QueueLength = 0;
		private String LocalProcessedFilename;
		private String ConvertedFile;
		private boolean done = false;
		private String servername;
		private String apikey;
		private Timer t = new Timer();
		private String LocalFilename;
		private Gson gson = new Gson();

		public void AddListener(IFileEventsListener listener) {
			this.list = listener;
		}

		public String getLocalFilename() {
			return LocalFilename;
		}

		public int getProgress() {
			return Progress;
		}

		public FileStatus getStatus() {
			return Status;
		}

		public int getPlaceInQueue() {
			return PlaceInQueue;
		}

		public int getQueueLength() {
			return QueueLength;
		}

		public String getLocalProcessedFilename() {
			return LocalProcessedFilename;
		}

		public String getConvertedFile() {
			return ConvertedFile;
		}

		protected File(String filename, String destfilename) {
			LocalFilename = filename;
			LocalProcessedFilename = destfilename;
		}

		protected void Upload(String apikey) {
			this.apikey = apikey;
			Status = FileStatus.UPLOADING;
			(new Uploader(this)).start();
		}

		protected void StartGetProgress() {
			t.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					// get progress
					try {
						// get the data...
						DefaultHttpClient httpclient = new DefaultHttpClient();
						HttpGet httpGet = new HttpGet(Panopticonize.SERVER
								+ "api.php?key=" + APIKey + "&a=progress&f="
								+ servername);
						HttpResponse response1 = httpclient.execute(httpGet);
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(response1.getEntity()
										.getContent()));
						// URL url = new URL("http://stackoverflow.com/");
						// new InputStreamReader(url.openStream()));
						String ss = null;
						String tt = "";
						while ((ss = reader.readLine()) != null)
							tt += ss;

						Hashtable ht = gson.fromJson(tt, Hashtable.class);
						if (ht.containsKey("code")) {
							throw new PanopticonizeException(Integer
									.parseInt(ht.get("code").toString()), ht
									.get("details").toString());
						}

						ServerData sd = gson.fromJson(tt, ServerData.class);

						if (sd.progress != Progress) {
							Progress = sd.progress;
							list.OnProcessProgressChanged(sd.progress);

							if (Status != FileStatus.PROCESSING) {
								Status = FileStatus.PROCESSING;
								list.OnStatusChanged(FileStatus.PROCESSING);
							}
						}

						if (sd.done == true && sd.link != "" && !done) {
							done = true;
							t.cancel();
							ConvertedFile = sd.link;
							Status = FileStatus.DOWNLOADING;
							list.OnStatusChanged(FileStatus.DOWNLOADING);

							// download
							Content r = Request
									.Get(Panopticonize.SERVER + "/" + sd.link)
									.execute().returnContent();
							FileOutputStream s = new FileOutputStream(
									LocalProcessedFilename);

							s.write(r.asBytes());
							s.close();
							Status = FileStatus.DONE;
							list.OnStatusChanged(FileStatus.DONE);

						}

						if (sd.q != PlaceInQueue) {
							PlaceInQueue = sd.q;
							QueueLength = sd.qtotal;
							list.OnPlaceInQueueChanged(sd.q, sd.qtotal);
						}
					} catch (Exception ex) {
						// do something here...

					}
				}
			}, 0, 1000);
		}

	}

	@SuppressWarnings("serial")
	class PanopticonizeException extends Exception {
		public int ErrorCode;
		
		public PanopticonizeException(int code, String message) {
			this.ErrorCode = code;
		}		
	}

	class ServerData {
		public String file = "";
		public int progress = 0;
		public boolean done = false;
		public int q = 0;
		public int qtotal = 0;
		public String error = "";
		public String link = "";
	}

	public class UploadListener implements Panopticonize.WriteListener {
		long total;
		Panopticonize.File file;

		public UploadListener(long total, Panopticonize.File file) {
			this.total = total;
			this.file = file;
		}

		@Override
		public void registerWrite(long amountOfBytesWritten) {
			file.list
					.OnUploadProgressChanged((int) ((amountOfBytesWritten / (double) total) * 100));
		}

	}

	public interface WriteListener {
		void registerWrite(long amountOfBytesWritten);
	}

	public class OutputStreamProgress extends OutputStream {

		private final OutputStream outstream;
		private volatile long bytesWritten = 0;
		private final WriteListener writeListener;

		public OutputStreamProgress(OutputStream outstream,
				WriteListener writeListener) {
			this.outstream = outstream;
			this.writeListener = writeListener;
		}

		@Override
		public void write(int b) throws IOException {
			outstream.write(b);
			bytesWritten++;
			writeListener.registerWrite(bytesWritten);
		}

		@Override
		public void write(byte[] b) throws IOException {
			outstream.write(b);
			bytesWritten += b.length;
			writeListener.registerWrite(bytesWritten);
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			outstream.write(b, off, len);
			bytesWritten += len;
			writeListener.registerWrite(bytesWritten);
		}

		@Override
		public void flush() throws IOException {
			outstream.flush();
		}

		@Override
		public void close() throws IOException {
			outstream.close();
		}
	}

	public class MultipartEntityWithProgressBar extends MultipartEntity {
		private OutputStreamProgress outstream;
		private WriteListener writeListener;

		@Override
		public void writeTo(OutputStream outstream) throws IOException {
			this.outstream = new OutputStreamProgress(outstream, writeListener);
			super.writeTo(this.outstream);
		}

		public MultipartEntityWithProgressBar(WriteListener writeListener) {
			super();
			this.writeListener = writeListener;
		}

		public MultipartEntityWithProgressBar(HttpMultipartMode mode,
				WriteListener writeListener) {
			super(mode);
			this.writeListener = writeListener;
		}

		public MultipartEntityWithProgressBar(HttpMultipartMode mode,
				String boundary, Charset charset, WriteListener writeListener) {
			super(mode, boundary, charset);
			this.writeListener = writeListener;
		}
	}
}

Download Source

Usage


class Program
{
	static void Main(string[] args)
	{
		Panopticonize panopticon = new Panopticonize("--my api key--");
		var f = panopticon.UploadForProcessing("--my file--");
		f.OnPlaceInQueueChanged += new Action(f_OnPlaceInQueueChanged);
		f.OnProcessProgressChanged += new Action(f_OnProgressChanged);
		f.OnUploadProgressChanged += new Action(f_OnUploadProgressChanged);
		f.OnStatusChanged += new Action(f_OnStatusChanged);
		Console.WriteLine("Uploading");
		while (true)
		{
			Thread.Sleep(200);
		}
	}

	static void f_OnUploadProgressChanged(int obj)
	{
		Console.WriteLine("Upload: " + obj);
	}

	static void f_OnStatusChanged(FileStatus obj)
	{
		Console.WriteLine("Status: " + obj);
	}

	static void f_OnProgressChanged(int obj)
	{
		Console.WriteLine("Progress: " + obj);
	}

	static void f_OnPlaceInQueueChanged(int obj,int obj2)
	{
		Console.WriteLine("In Queue: " + obj + " of " + obj2);
	}
}	  
	  
	  

Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Web.Script.Serialization;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Collections;

namespace Panopticonize
{
    public enum FileStatus {UPLOADING, INQUEUE, PROCESSING, DOWNLOADING, DONE};

    public class PanopticonizeException : Exception
    {
        public PanopticonizeException(int code, string message):base(message)
        {
            this.ErrorCode = code;
        }
        public int ErrorCode { get; internal set; }
    }

    public class File
    {
        public string LocalFilename { get; internal set; }
        public int Progress { get; internal set; }
        public FileStatus Status { get; internal set; }
        public int PlaceInQueue { get; internal set; } 
        public int QueueLength { get; internal set; }
        public string LocalProcessedFilename { get; internal set; }
        public event Action<int> OnProcessProgressChanged;
        public event Action<int> OnUploadProgressChanged;
        public event Action<FileStatus> OnStatusChanged;
        public event Action<int,int> OnPlaceInQueueChanged;
        public string ConvertedFile { get; internal set; }

        private bool done = false;

        private string servername;
        private string apikey;

        internal File(string filename,string destfilename)
        {
            LocalFilename = filename;
            LocalProcessedFilename = destfilename;
        }
        System.Timers.Timer t = new System.Timers.Timer();
        internal void Upload(string apikey)
        {
            this.apikey = apikey;
            Status = FileStatus.UPLOADING;
            Thread thread = new Thread(new ThreadStart(() => {
                Uploader u = new Uploader();
                u.OnUploadProgress += new Action<int>(u_OnUploadProgress);
                try
                {
                    string s = u.UploadFileEx(LocalFilename, Panopticonize.SERVER + "/api.php?key=" + apikey + "&a=upload&", "files", "video/mp4", null, new CookieContainer());
                    Hashtable sdd = (Hashtable)ser.Deserialize<Hashtable>(s);
                    if (sdd.ContainsKey("code"))
                    {
                        throw new PanopticonizeException(Int32.Parse(sdd["code"].ToString()), sdd["details"].ToString());
                    }
                    servername = sdd["id"].ToString();
                    //when upload complete
                    Status = FileStatus.INQUEUE;
                    if (OnStatusChanged != null)
                        OnStatusChanged(FileStatus.INQUEUE);

                    t.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
                    t.Elapsed += new ElapsedEventHandler(t_Elapsed);
                    t.Start();
                    web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
                    web.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(web_DownloadFileCompleted);
                    t_Elapsed(null, null);
                }
                catch (Exception e)
                {
                    throw e;
                }                
            }));
            thread.Start();            
        }

        void web_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Status = FileStatus.DONE;
            if (OnStatusChanged != null)
                OnStatusChanged(FileStatus.DONE);
        }

        void u_OnUploadProgress(int obj)
        {
            if (OnUploadProgressChanged != null)
            {
                OnUploadProgressChanged(obj);
            }
        }
        
        void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                ServerData sd = ser.Deserialize<ServerData>(e.Result);
                if (sd.progress != Progress)
                {
                    Progress = sd.progress;
                    if (OnProcessProgressChanged != null)
                    {
                        OnProcessProgressChanged(sd.progress);
                    }
                    if (Status != FileStatus.PROCESSING)
                    {
                        Status = FileStatus.PROCESSING;
                        if (OnStatusChanged != null)
                            OnStatusChanged(FileStatus.PROCESSING);
                    }
                }

                if (sd.done == true && sd.link != "" && !done)
                {
                    done = true;
                    t.Stop();
                    ConvertedFile = sd.link;
                    Status = FileStatus.DOWNLOADING;
                    if (OnStatusChanged != null)
                        OnStatusChanged(FileStatus.DOWNLOADING);

                    //download
                    web.DownloadFileAsync(new Uri(Panopticonize.SERVER + "/" + sd.link), LocalProcessedFilename);
                }

                if (sd.q != PlaceInQueue)
                {
                    PlaceInQueue = sd.q;
                    QueueLength = sd.qtotal;
                    if (OnPlaceInQueueChanged != null)
                    {
                        OnPlaceInQueueChanged(sd.q,sd.qtotal);
                    }
                }
            }
            catch (Exception ex)
            {
                //do something here...
            }
        }

        JavaScriptSerializer ser = new JavaScriptSerializer();
        WebClient web = new WebClient();

        void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            //get status...
            web.DownloadStringAsync(new Uri(Panopticonize.SERVER+"/api.php?key="+apikey+"&a=progress&f="+servername));
        }
    }

    class ServerData
    {
        public string file="";
	    public int progress=0;
	    public bool done = false;
	    public int q = 0;
	    public int qtotal = 0;
	    public string error = "";
	    public string link = "";
    }

    class Uploader
    {
        public event Action<int> OnUploadProgress;

        internal string UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies)
        {
            if ((fileFormName == null) ||
                (fileFormName.Length == 0))
            {
                fileFormName = "file";
            }

            if ((contenttype == null) ||
                (contenttype.Length == 0))
            {
                contenttype = "application/octet-stream";
            }

            string postdata;
            postdata = "?";
            Uri uri;
            if (querystring != null)
            {
                foreach (string key in querystring.Keys)
                {
                    postdata += key + "=" + querystring.Get(key) + "&";
                }
                uri = new Uri(url + postdata);
            }
            else
            {
                uri = new Uri(url);
            }

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
            webrequest.CookieContainer = cookies;
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";


            // Build up the post message header
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append(fileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(Path.GetFileName(uploadfile));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append(contenttype);
            sb.Append("\r\n");
            sb.Append("\r\n");

            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

            // Build the trailing boundary string as a byte array
            // ensuring the boundary appears on a line by itself
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
            webrequest.ContentLength = length;

            Stream requestStream = webrequest.GetRequestStream();

            // Write out our post header
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Write out the file contents
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;

            int total = 0;
            int max = (int)fileStream.Length;

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
                total += bytesRead;
                if (OnUploadProgress != null)
                    OnUploadProgress((int)((total / (double)length) * 100));
            }

            // Write out the trailing boundary
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            WebResponse responce = webrequest.GetResponse();
            Stream s = responce.GetResponseStream();
            StreamReader sr = new StreamReader(s);

            return sr.ReadToEnd();
        }
    }

    public class Panopticonize
    {
        internal const string SERVER = "http://panopticonize.com/";

        public string APIKey { get; private set; }
        public Panopticonize(string apikey)
        {
            APIKey = apikey;
        }

        public File UploadForProcessing(string filename,string destination)
        {
            File f = new File(filename,destination);
            f.Upload(APIKey);
            return f;
        }

        public File UploadForProcessing(string filename)
        {
            return UploadForProcessing(filename, filename + ".panop.mp4");
        }
    }
}
	  

Coming soon

HTTP API

If you want to use another language, you can just connect to Panopticonize using standard HTTP.

Uploading POST a file using multipart/formdata with the fieldname 'files' to the following url:
http://panopticonize.com/api.php?key=apikey&a=upload

This returns a JSON object with the id of the file for use in progress and retrieval.
Getting Progress Send a GET request to the following url:
http://panopticonize.com/api.php?key=apikey&a=progress&f=fileid

This returns a JSON object with the progress details and place in the queue of the file:
Downloading Send a GET request to the following url:
http://panopticonize.com/filesp/fileid

Error Codes

All errors will be accompanied by a HTTP 400 Invalid Request Header, and the following in JSON.
code
details
100
No API Key Supplied - You need to sign up for an API key and supply this with each call to the API.
101
Invalid API Key
102
Banned API Key
200
Invalid Command
201
Upload Failed
202
Unknown Command
300
No file given for progress report
301
File does not Exist
Panopticonize