Last active
March 25, 2017 19:17
-
-
Save Sciss/bea9022d90a4f0ad7556e8fa283ff459 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer | |
import com.ning.http.client | |
import com.ning.http.client.AsyncHandler.STATE | |
import com.ning.http.client.HttpResponseHeaders | |
import com.ning.http.client.resumable.ResumableAsyncHandler | |
import dispatch.OkHandler | |
object FileWithProgress { | |
def apply(file: File)(progress: (Long, Long) => Unit): ResumableAsyncHandler[_] = { | |
val handler = new client.resumable.ResumableAsyncHandler with OkHandler[Nothing] { | |
private[this] val raf = new java.io.RandomAccessFile(file, "rw") | |
if (raf.length() > 0L) raf.setLength(0L) | |
private[this] var fileSize = -1L | |
override def onHeadersReceived(headers: HttpResponseHeaders): STATE = { | |
val res: STATE = super.onHeadersReceived(headers) | |
if (res == STATE.CONTINUE) { | |
val contentLengthHeader = headers.getHeaders.getFirstValue("Content-Length") | |
if (contentLengthHeader != null) { | |
fileSize = java.lang.Long.parseLong(contentLengthHeader) | |
} | |
} | |
res | |
} | |
setResumableListener( | |
new client.extra.ResumableRandomAccessFileListener(raf) { | |
override def onBytesReceived(buffer: ByteBuffer): Unit = { | |
super.onBytesReceived(buffer) | |
if (fileSize > 0L) { | |
val pos = raf.length() | |
progress(pos, fileSize) | |
} | |
} | |
} | |
) | |
} | |
handler | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment