Skip to content

Commit

Permalink
proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
strukturart committed Dec 15, 2024
1 parent 650009e commit a07b35c
Show file tree
Hide file tree
Showing 10 changed files with 173 additions and 44 deletions.
105 changes: 76 additions & 29 deletions application/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,14 @@ if (userAgent && userAgent.includes("KAIOS")) {
}

let current_article = "";
const proxy = "https://corsproxy.io/?";
const proxy = "https://api.cors.lol/?url=";

let default_settings = {
"opml_url":
"https://raw.githubusercontent.com/strukturart/feedolin/master/example.opml",
"opml_local": "",
"proxy_url": "https://corsproxy.io/?",
"cache_time": 1000,
"proxy_url": "https://api.cors.lol/?url=",
"cache_time": 3600000,
};
//store all articles id to compare
let articlesID = [];
Expand All @@ -120,14 +120,9 @@ localforage
});

let reload_data = () => {
articles = [];
localforage.setItem("last_channel_filter", channel_filter).then(() => {
side_toaster("load data", 3000);

start_loading();
});

setTimeout(() => {}, 3000);
};

function add_read_article(id) {
Expand Down Expand Up @@ -347,32 +342,55 @@ let raw = (i) => {

const fetchOPML = (url) => {
let t = url;
if (status.notKaiOS) t = settings.proxy_url + url;

const xhr = new XMLHttpRequest({ "mozSystem": true });
let xhr = null;
if (status.notKaiOS) {
t = settings.proxy_url + url;
xhr = new XMLHttpRequest();
} else {
xhr = new XMLHttpRequest({ "mozSystem": true });
}

xhr.open("GET", t, true);
xhr.setRequestHeader("Accept", "application/xml");

xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
// Success
side_toaster("Data loaded successfully", 3000);
load_feeds(xhr.responseText);
} else {
// HTTP error handling
console.log(`HTTP error! Status: ${xhr.status}`);
handleHttpError(xhr.status);
}
};

xhr.onerror = function (error) {
m.route.set("/start");

side_toaster("Error fetching the OPML file" + error, 4000);
xhr.onerror = function () {
handleRequestError();
};

xhr.send();
};

const handleHttpError = (status) => {
console.error(`HTTP Error: Status ${status}`);
side_toaster("OPML file not reachable", 4000);

// Route back to start if on intro
let r = m.route.get();
if (r.startsWith("/intro")) {
m.route.set("/start");
}
};

const handleRequestError = () => {
console.error("Network error occurred during the request.");
side_toaster("OPML file not reachable", 3000);

// Route back to start if on intro
let r = m.route.get();
if (r.startsWith("/intro")) {
m.route.set("/start");
}
};

const load_feeds = async (data) => {
if (data) {
let downloadList;
Expand All @@ -392,7 +410,7 @@ const load_feeds = async (data) => {
settings.last_update = new Date();
localforage.setItem("settings", settings);
} catch (error) {
alert(error);
console.log(error);
}
} else {
alert("Generated download list is empty.");
Expand Down Expand Up @@ -456,8 +474,6 @@ const fetchContent = async (feed_download_list) => {
const checkIfAllFeedsLoaded = () => {
channel_filter = localStorage.getItem("last_channel_filter");
if (completedFeeds === totalFeeds) {
m.route.set("/start");

console.log("All feeds are loaded");
// All feeds are done loading, you can proceed with further actions
//cache data
Expand All @@ -484,6 +500,9 @@ const fetchContent = async (feed_download_list) => {
.catch((err) => {
console.error("Feeds cached", err);
});

let r = m.route.get();
if (r.startsWith("/intro")) m.route.set("/start");
}
};

Expand Down Expand Up @@ -561,7 +580,7 @@ const fetchContent = async (feed_download_list) => {
});
} else {
let xhr = new XMLHttpRequest({ "mozSystem": true });
xhr.timeout = 5000;
xhr.timeout = 2000;

let url = e.url;
if (status.notKaiOS) {
Expand Down Expand Up @@ -818,13 +837,12 @@ localforage
.setItem("settings", settings)
.then(function (value) {})
.catch(function (err) {
// This code runs if there were any errors
console.log(err);
});
}
settings = value;
//todo set value in settings view, default is 1sec
settings.cache_time = settings.cache_time || 1000;
//todo set value in settings view, default is 1h
settings.cache_time = settings.cache_time || 3600000;

if (settings.last_update) {
status.last_update_duration =
Expand Down Expand Up @@ -1534,6 +1552,9 @@ if ("b2g" in navigator) {
console.log(e);
}
}
if (navigator.mozAlarms) {
globalAudioElement.mozAudioChannelType = "content";
}

let hasPlayedAudio = [];

Expand Down Expand Up @@ -1642,7 +1663,6 @@ const AudioPlayerView = {
document
.querySelector("div.button-left")
.addEventListener("click", function () {
alert("j");
status.sleepTimer
? stopTimer()
: startTimer(settings.sleepTimer * 60 * 1000);
Expand Down Expand Up @@ -2209,6 +2229,8 @@ var settingsView = {
},
},
[
m("option", { value: "1" }, "1"),
m("option", { value: "5" }, "5"),
m("option", { value: "10" }, "10"),
m("option", { value: "20" }, "20"),
m("option", { value: "30" }, "30"),
Expand Down Expand Up @@ -2805,6 +2827,7 @@ window.addEventListener("offline", () => {
});

window.addEventListener("beforeunload", (event) => {
localforage.setItem("last_channel_filter", channel_filter).then(() => {});
const entries = window.performance.getEntriesByType("navigation");

// For older browsers (fallback)
Expand Down Expand Up @@ -2874,6 +2897,12 @@ try {
} catch (e) {}

//worker sleep mode
if (navigator.mozAlarms) {
navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
globalAudioElement.pause();
status.sleepTimer = false;
});
}

let worker;

Expand All @@ -2884,14 +2913,32 @@ try {
}

function startTimer(timerDuration) {
worker.postMessage({ action: "start", duration: timerDuration });
side_toaster("sleep mode on", 3000);
//KaiOS2
if (navigator.mozAlarms) {
let sleepDuration = settings.sleepTimer * 60 * 1000; // Convert minutes to milliseconds
let targetTime = new Date(Date.now() + sleepDuration); // Add duration to current time

var request = navigator.mozAlarms.add(targetTime, "honorTimezone");

request.onsuccess = function () {
status.alarmId = this.result;
};
}

status.sleepTimer = true;
side_toaster("sleep mode on", 3000);

worker.postMessage({ action: "start", duration: timerDuration });
}

function stopTimer() {
worker.postMessage({ action: "stop" });
if (navigator.mozAlarms) {
navigator.mozAlarms.remove(status.alarmId);
}
status.sleepTimer = false;

side_toaster("sleep mode off", 3000);
worker.postMessage({ action: "stop" });
}

worker.onmessage = function (event) {
Expand Down
2 changes: 1 addition & 1 deletion application/manifest.webapp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "2.0.15",
"version": "2.0.17",
"name": "feedolin",
"description": "Feedolin is an RSS / Atom / Mastodon reader and podcast player. It is intended for users who already use an rss reader client and want to read their feeds on a kaios device. the list of subscribed websites / podcasts is managed locally or online in an opml file.",
"launch_path": "/index.html",
Expand Down
4 changes: 1 addition & 3 deletions application/manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@
],

"b2g_features": {
"version": "1.8.128",
"version": "1.8.132",
"id": "feedolin",
"subtitle": "RSS Reader and Mastodon Reader",
"core": true,
"type": "privileged",
"display": "fullscreen",
"origin": "http://feedolin.localhost",

"developer": {
"name": "strukturart",
"url": "https://github.com/strukturart/feedolin"
Expand Down
2 changes: 1 addition & 1 deletion application/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ self.addEventListener("systemmessage", async (evt) => {
const userAgent = navigator.userAgent || "";

if (userAgent && !userAgent.includes("KAIOS")) {
const CACHE_NAME = "pwa-cache-v0.1181";
const CACHE_NAME = "pwa-cache-v0.1197";
const FILE_LIST_URL = "/file-list.json"; // URL of the JSON file containing the array of files

self.addEventListener("install", (event) => {
Expand Down
2 changes: 1 addition & 1 deletion docs/index.339e55c4.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/index.f0337e49.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/manifest.webapp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "2.0.15",
"version": "2.0.17",
"name": "feedolin",
"description": "Feedolin is an RSS / Atom / Mastodon reader and podcast player. It is intended for users who already use an rss reader client and want to read their feeds on a kaios device. the list of subscribed websites / podcasts is managed locally or online in an opml file.",
"launch_path": "/index.html",
Expand Down
8 changes: 2 additions & 6 deletions docs/manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@
],

"b2g_features": {
"version": "1.8.125",
"version": "1.8.132",
"id": "feedolin",
"subtitle": "RSS Reader and Mastodon Reader",
"core": true,
"type": "privileged",
"display": "fullscreen",
"origin": "http://feedolin.localhost",

"developer": {
"name": "strukturart",
"url": "https://github.com/strukturart/feedolin"
Expand All @@ -58,9 +56,7 @@
"desktop-notification": {
"description": "Needed to fire system notifications"
},
"alarms": {
"description": "Required to schedule alarms"
},

"feature-detection": {
"description": "query which keys are available"
},
Expand Down
2 changes: 1 addition & 1 deletion docs/sw.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

88 changes: 88 additions & 0 deletions proxy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php
// Enable CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Requested-With");

// Parse input data
$requestBody = file_get_contents("php://input");
$isJsonRequest = false;
$requestData = json_decode($requestBody, true);
if (json_last_error() === JSON_ERROR_NONE) {
$isJsonRequest = true;
}

// Determine request parameters
$method = $_REQUEST['method'] ?? 'GET'; // Default to GET if method is not provided
$url = $isJsonRequest ? $requestData['cors'] ?? null : ($_REQUEST['cors'] ?? null);

// Handle direct query string URL (e.g., ?https://rss.strukturart.com/...)
if (!$url && isset($_SERVER['QUERY_STRING']) && filter_var($_SERVER['QUERY_STRING'], FILTER_VALIDATE_URL)) {
$url = $_SERVER['QUERY_STRING'];
}

if (!$url) {
echo json_encode(["message" => "PROXY ACCESS DENIED! URL not specified"]);
exit();
}

// Prepare headers
$headers = [];
foreach (getallheaders() as $key => $value) {
if (in_array(strtolower($key), ['content-type', 'authorization', 'x-requested-with'])) {
$headers[] = "$key: $value";
}
}

// Prepare CURL options
$curl = curl_init();
switch (strtoupper($method)) {
case 'POST':
$postData = $isJsonRequest ? $requestData : $_POST;
unset($postData['method'], $postData['cors']);
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $isJsonRequest ? json_encode($postData) : http_build_query($postData),
]);
break;

case 'GET':
$getData = $isJsonRequest ? $requestData : $_GET;
unset($getData['method'], $getData['cors']);
$queryString = http_build_query($getData);
curl_setopt($curl, CURLOPT_URL, $url . ($queryString ? "?$queryString" : ""));
break;

default:
echo json_encode(["message" => "Proxy only supports POST and GET requests"]);
exit();
}

curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false, // Disable for development, enable in production
CURLOPT_HTTPHEADER => $headers,
]);

// Execute CURL request
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

if ($error) {
echo json_encode(["error" => $error]);
exit();
}

// Set response content type if possible
if (json_decode($response) !== null) {
header('Content-Type: application/json');
} elseif (strpos($response, '<?xml') === 0) {
header('Content-Type: application/xml');
}

// Output the response
echo $response;

0 comments on commit a07b35c

Please sign in to comment.