Skip to content

Commit

Permalink
refact: remove poor code
Browse files Browse the repository at this point in the history
  • Loading branch information
heliomarpm committed Jul 7, 2024
1 parent 570e76c commit af049b2
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 71 deletions.
73 changes: 29 additions & 44 deletions app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ const MSG_DRM_PROTECTED = translate("Contains DRM protection and cannot be downl
const HTTP_TIMEOUT = 40000; // 40 segundos

const loggers = [];

let repoAccount = "heliomarpm";
let udemyService;

Expand Down Expand Up @@ -630,8 +629,8 @@ async function renderDownloads() {
// Executa todas as Promessas em paralelo
Promise.all(promises)
.then(() => ui.busyLoadDownloads(false))
.catch(error => {
console.error("Error adding courses:", error);
.catch(e => {
console.error("Error adding courses:", e);
ui.busyLoadDownloads(false);
});

Expand Down Expand Up @@ -793,32 +792,15 @@ async function fetchCourses(isSubscriber) {
renderDownloads();
}
})
.catch(error => {
const statusCode = (error.response?.status || 0).toString() + (error.code ? ` :${error.code}` : "");
appendLog(`EFETCHING_COURSES: ${error.code}(${statusCode})`, error.message);
.catch(e => {
const statusCode = (e.response?.status || 0).toString() + (e.code ? ` :${e.code}` : "");
appendLog(`EFETCHING_COURSES: ${e.code}(${statusCode})`, e.message);
//showAlert(error.message, "Fetching Courses");
throw utils.newError("EFETCHING_COURSES", error.message);
throw utils.newError("EFETCHING_COURSES", e.message);
})
.finally(() => {
ui.busyLoadCourses(false);
});
return;


try {
const courses = await udemyService.fetchCourses(PAGE_SIZE, isSubscriber);
console.log("fetch courses", courses);
renderCourses(courses);
if (Settings.downloadedCourses) {
renderDownloads();
}

} catch (error) {
appendLog("Error Fetching Courses", error);
showAlert(error.message, "Fetching Courses");
} finally {
ui.busyLoadCourses(false);
}
}

function loadMore(loadMoreButton) {
Expand All @@ -835,9 +817,9 @@ function loadMore(loadMoreButton) {
} else {
$button.data("url", resp.next);
}
}).catch(error => {
const statusCode = (error.response?.status || 0).toString() + (error.code ? ` :${error.code}` : "");
appendLog(`loadMore_Error: (${statusCode})`, error);
}).catch(e => {
const statusCode = (e.response?.status || 0).toString() + (e.code ? ` :${e.code}` : "");
appendLog(`loadMore_Error: (${statusCode})`, e);
}).finally(() => {
ui.busyLoadCourses(false);
});
Expand Down Expand Up @@ -1130,9 +1112,8 @@ function startDownload($course, courseData, subTitle = "") {
$downloadQuality.show();

function stopDownload(isEncryptedVideo) {
if (downloader) {
const dl = downloader._downloads[downloader._downloads.length - 1];
dl.stop();
if (downloader.downloads?.length) {
downloader._downloads[downloader._downloads.length - 1].stop();
$pauseButton.addClass("disabled");
$resumeButton.removeClass("disabled");

Expand All @@ -1143,10 +1124,8 @@ function startDownload($course, courseData, subTitle = "") {
}

function resumeDownload() {
if (downloader) {
const dl = downloader._downloads[downloader._downloads.length - 1];
dl.resume();

if (downloader._downloads?.length) {
downloader._downloads[downloader._downloads.length - 1].resume();
$pauseButton.removeClass("disabled");
$resumeButton.addClass("disabled");
}
Expand Down Expand Up @@ -1258,7 +1237,7 @@ function startDownload($course, courseData, subTitle = "") {
if (dl.status === -1 && dl.stats.total.size == 0 && fs.existsSync(dl.filePath)) {
dl.emit("end");
clearInterval(timerDownloader);
} else if (dl.status === -1) {
} else if (dl.status === -1) {
appendLog("Download error, retrying... ", { url: dl.url } )
axios({
timeout: HTTP_TIMEOUT,
Expand Down Expand Up @@ -1456,7 +1435,7 @@ function startDownload($course, courseData, subTitle = "") {
let download_this_sub = availables[0] || Object.keys(subtitles)[0] || "";
// Prefer non "[Auto]" subs (likely entered by the creator of the lecture.)
if (availables.length > 1) {
for (const key in availables) {
for (const key of availables) {
if (availables[key].indexOf("[Auto]") == -1 || availables[key].indexOf(`[${translate("Auto")}]`) == -1) {
download_this_sub = availables[key];
break;
Expand Down Expand Up @@ -1590,15 +1569,15 @@ function startDownload($course, courseData, subTitle = "") {
);

// $lecture_name.html(`${courseData["chapters"][chapterIndex].name}\\${lectureName}`);
const skipLecture = Number(Settings.download.type) === Settings.DownloadType.OnlyAttachments;
const skipLecture = (Settings.download.type == Settings.DownloadType.OnlyAttachments);

if (lectureType !== "application/x-mpegURL") {
if (lectureType !== "application/x-mpegurl") {

if (fs.existsSync(seqName.fullPath) || skipLecture) {
endDownloadAttachment();
return;
}

if (fs.existsSync(seqName.fullPath + ".mtd") && !fs.statSync(seqName.fullPath + ".mtd").size) {
fs.unlinkSync(seqName.fullPath + ".mtd");
}
Expand All @@ -1607,7 +1586,7 @@ function startDownload($course, courseData, subTitle = "") {
appendLog("Video Encrypted", `Chapter: ${chapterName}\nLecture: ${lectureName}`);
}
else {
if (fs.existsSync(seqName.fullPath + ".mtd") && !skipLecture) {
if (fs.existsSync(seqName.fullPath + ".mtd")) {
var dl = downloader.resumeDownload(seqName.fullPath);
} else {
var dl = downloader.download(lectureData.src, seqName.fullPath);
Expand Down Expand Up @@ -1774,7 +1753,7 @@ function sendNotification(pathCourse, courseName, urlImage = null) {
}

function clearLogArea() {
loggers = [];
loggers.length = 0;
$(".ui.logger.section .ui.list").html("");
clearBagdeLoggers();
}
Expand All @@ -1784,9 +1763,15 @@ function clearBagdeLoggers() {
$("#badge-logger").hide();
}

function appendLog(title, error = "" | Error) {
const description = error instanceof Error
? error.message
/**
* Function to append a log entry with the specified title and error.
*
* @param {string} title - The title of the log entry.
* @param {string|Error|object} error - The error message or Error object.
*/
function appendLog(title, error) {
const description = error instanceof Error
? error.message
: (typeof error == "object" ? JSON.stringify(error): error);

// item added to list to display
Expand Down
4 changes: 2 additions & 2 deletions app/core/services/m3u8.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ class M3U8Service {
}
this._playlist = this._extractUrlsAndQualities(playlistContent);
return this._playlist;
} catch (error) {
throw error;
} catch (e) {
throw e;
}
}

Expand Down
51 changes: 26 additions & 25 deletions app/core/services/udemy.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class UdemyService {
const isEncrypted = Boolean(asset.media_license_token);
if (stream_urls) {
console.log(`Preparing streams for asset id: ${asset.id}`);
const streams = await this._convertToStreams(stream_urls, isEncrypted, asset.title );
const streams = await this._convertToStreams(stream_urls, isEncrypted, asset.title);

delete el.asset.stream_urls;
delete el.asset.media_sources;
Expand All @@ -72,17 +72,17 @@ class UdemyService {

/**
* Transforms media sources into a standardized format.
*
*
* @param {Array<Object>} streamUrls - The array of stream URLs.
* @param {boolean} isEncrypted - Indicates if the media is encrypted.
* @returns {Promise<{
* minQuality: string,
* maxQuality: string,
* minQuality: string,
* maxQuality: string,
* isEncrypted: boolean
* sources: { [key: string]: { type: string, url: string } }
* }>} - The transformed media sources.
*/
async _convertToStreams(streamUrls, isEncrypted, title="") {
async _convertToStreams(streamUrls, isEncrypted, title = "") {
try {
if (!streamUrls) {
throw this._error("ENO_STREAMS", "No streams found to convert");
Expand Down Expand Up @@ -139,25 +139,25 @@ class UdemyService {
}

// playlist.forEach(item => {
// const numericQuality = item.quality;

// if (numericQuality < minQuality) {
// minQuality = numericQuality;
// }
// if (numericQuality > maxQuality) {
// maxQuality = numericQuality;
// }
// if (!sources[numericQuality.toString()]) {
// sources[numericQuality.toString()] = { type, url: item.url }
// }
// const numericQuality = item.quality;

// if (numericQuality < minQuality) {
// minQuality = numericQuality;
// }
// if (numericQuality > maxQuality) {
// maxQuality = numericQuality;
// }
// if (!sources[numericQuality.toString()]) {
// sources[numericQuality.toString()] = { type, url: item.url }
// }
// });
}
}
}
});

await Promise.all(promises);
console.log(`All stream urls converted for assetName: ${title}`);
console.log(`All stream urls converted for assetName: ${title}`);

return {
minQuality: minQuality === Number.MAX_SAFE_INTEGER ? "auto" : minQuality.toString(),
Expand Down Expand Up @@ -192,9 +192,9 @@ class UdemyService {
// Armazene o resultado no cache
this.#cache.set(url, response.data);
return response.data;
} catch (error) {
console.error(`Error fetching URL: ${url}`, error);
throw error;
} catch (e) {
console.error(`Error fetching URL: ${url}`, e);
throw e;
}
}

Expand All @@ -218,9 +218,9 @@ class UdemyService {
// Armazene o resultado no cache
this.#cache.set(url, response.data);
return response.data;
} catch (error) {
console.error(`Error fetching URL: ${url}`, error);
throw error;
} catch (e) {
console.error(`Error fetching URL: ${url}`, e);
throw e;
}
}

Expand Down Expand Up @@ -288,12 +288,13 @@ class UdemyService {
* Fetches the course content for a given course ID and content type.
*
* @param {number} courseId - The ID of the course.
* @param {'less' | 'all' | 'lectures' | 'attachments'} [contentType='less'] - The type of content to fetch.
* @param {'less' | 'all' | 'lectures' | 'attachments'} [contentType='all'] - The type of content to fetch.
* @return {Promise<any>} - The course content data.
*/
async fetchCourseContent(courseId, contentType = "less" | "all" | "lectures" | "attachments", httpTimeout = this.#timeout) {
async fetchCourseContent(courseId, contentType, httpTimeout = this.#timeout) {
let url = `/courses/${courseId}/cached-subscriber-curriculum-items?page_size=10000`

contentType = (contentType || "less").toLowerCase();
if (contentType !== "less") url += "&fields[lecture]=id,title";
if (contentType === "all") url += ",asset,supplementary_assets";
if (contentType === "lectures") url += ",asset";
Expand Down

0 comments on commit af049b2

Please sign in to comment.