Skip to content

Commit

Permalink
[YouTube] Improve download speed (#9948)
Browse files Browse the repository at this point in the history
  • Loading branch information
Theta-Dev authored May 1, 2023
1 parent ed17811 commit fb00ee8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ public void run() {
long lowestSize = Long.MAX_VALUE;

for (int i = 0; i < mMission.urls.length && mMission.running; i++) {
mConn = mMission.openConnection(mMission.urls[i], true, -1, -1);
mConn = mMission.openConnection(mMission.urls[i], true, 0, 0);
mMission.establishConnection(mId, mConn);
dispose();

if (Thread.interrupted()) return;
long length = Utility.getContentLength(mConn);
long length = Utility.getTotalContentLength(mConn);

if (i == 0) {
httpCode = mConn.getResponseCode();
Expand All @@ -84,14 +84,14 @@ public void run() {
}
} else {
// ask for the current resource length
mConn = mMission.openConnection(true, -1, -1);
mConn = mMission.openConnection(true, 0, 0);
mMission.establishConnection(mId, mConn);
dispose();

if (!mMission.running || Thread.interrupted()) return;

httpCode = mConn.getResponseCode();
mMission.length = Utility.getContentLength(mConn);
mMission.length = Utility.getTotalContentLength(mConn);
}

if (mMission.length == 0 || httpCode == 204) {
Expand Down
27 changes: 24 additions & 3 deletions app/src/main/java/us/shandian/giga/util/Utility.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package us.shandian.giga.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
Expand All @@ -29,8 +26,10 @@
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.Locale;
import java.util.Random;

import okio.ByteString;
import us.shandian.giga.get.DownloadMission;

public class Utility {

Expand Down Expand Up @@ -232,6 +231,28 @@ public static long getContentLength(HttpURLConnection connection) {
return -1;
}

/**
* Get the content length of the entire file even if the HTTP response is partial
* (response code 206).
* @param connection http connection
* @return content length
*/
public static long getTotalContentLength(final HttpURLConnection connection) {
try {
if (connection.getResponseCode() == 206) {
final String rangeStr = connection.getHeaderField("Content-Range");
final String bytesStr = rangeStr.split("/", 2)[1];
return Long.parseLong(bytesStr);
} else {
return getContentLength(connection);
}
} catch (Exception err) {
// nothing to do
}

return -1;
}

private static String pad(int number) {
return number < 10 ? ("0" + number) : String.valueOf(number);
}
Expand Down

0 comments on commit fb00ee8

Please sign in to comment.