Skip to content

The free and privacy-friendly screen recorder with no limits 🎥

Fix saving to Google Drive + PiP for Instant Mode

Alyssa X6b91785f371f
diff --git a/src/manifest.json b/src/manifest.json
index 12a2366..7b8b2b1 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.0.3",
+ "version": "4.0.4",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/drive/handleSaveToDrive.js b/src/pages/Background/drive/handleSaveToDrive.js
index f4c2e4c..a99bac4 100644
--- a/src/pages/Background/drive/handleSaveToDrive.js
+++ b/src/pages/Background/drive/handleSaveToDrive.js
@@ -8,21 +8,18 @@ const findOrCreateScreenityFolder = async (token) => {
"Content-Type": "application/json",
});
- // Try to find existing folder
const query = encodeURIComponent(
`name='Screenity' and mimeType='application/vnd.google-apps.folder' and trashed=false`
);
+
const searchRes = await fetch(
`https://www.googleapis.com/drive/v3/files?q=${query}&fields=files(id,name)`,
{ headers }
);
const result = await searchRes.json();
- if (result.files?.length) {
- return result.files[0].id; // Folder already exists
- }
+ if (result.files?.length) return result.files[0].id;
- // Otherwise, create the folder
const createRes = await fetch(`https://www.googleapis.com/drive/v3/files`, {
method: "POST",
headers,
@@ -36,191 +33,138 @@ const findOrCreateScreenityFolder = async (token) => {
return newFolder.id;
};
-const saveToDrive = async (videoBlob, fileName, sendResponse) => {
- async function getAuthTokenFromStorage() {
- return new Promise((resolve, reject) => {
- chrome.storage.local.get(["token"], async (result) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError));
- } else {
- const token = result.token;
- if (!token || token === null) {
- // Token is not set, trigger sign-in
- const newToken = await signIn();
- if (!newToken || newToken === null) {
- // Sign-in failed, throw an error
- reject(new Error("Sign-in failed"));
- }
- resolve(newToken);
- } else {
- // Token is set, check if it has expired
- let payload;
- try {
- payload = JSON.parse(atob(token.split(".")[1]));
- } catch (err) {
- // Token is invalid, refresh it
- chrome.identity.getAuthToken(
- { interactive: true },
- (newToken) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError));
- } else {
- resolve(newToken);
- }
- }
- );
- return;
- }
-
- const expirationTime = payload.exp * 1000; // Convert to milliseconds
- const currentTime = Date.now();
- if (currentTime >= expirationTime) {
- // Token has expired, refresh it
- chrome.identity.getAuthToken(
- { interactive: true },
- (newToken) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError));
- } else {
- resolve(newToken);
- }
- }
- );
- } else {
- // Token is still valid
- resolve(token);
- }
- }
- }
- });
- });
- }
-
- return new Promise(async (resolve, reject) => {
- try {
- // Get the access token from Chrome storage
- let token = await getAuthTokenFromStorage();
-
- if (!token || token === null) {
- throw new Error("Sign-in failed");
+const getAuthTokenFromStorage = async () => {
+ return new Promise((resolve, reject) => {
+ chrome.storage.local.get(["token"], async (result) => {
+ if (chrome.runtime.lastError) {
+ reject(new Error(chrome.runtime.lastError));
+ return;
}
- // Upload the video to Google Drive
- const headers = new Headers({
- Authorization: `Bearer ${token}`,
- "Content-Type": videoBlob.type,
- });
-
- const uploadResponse = await fetch(
- "https://www.googleapis.com/upload/drive/v3/files?uploadType=media",
- {
- method: "POST",
- headers,
- body: videoBlob,
- }
- );
-
- if (!uploadResponse.ok) {
- throw new Error(
- `Error uploading to Google Drive: ${uploadResponse.status}`
- );
+ const token = result.token;
+ if (!token) {
+ const newToken = await signIn();
+ if (!newToken) reject(new Error("Sign-in failed"));
+ else resolve(newToken);
+ return;
}
- const responseData = await uploadResponse.json();
- const fileId = responseData.id;
-
- if (!fileId) {
- throw new Error("File ID is undefined");
+ let payload;
+ try {
+ payload = JSON.parse(atob(token.split(".")[1]));
+ } catch {
+ chrome.identity.getAuthToken({ interactive: true }, (newToken) => {
+ if (chrome.runtime.lastError)
+ reject(new Error(chrome.runtime.lastError));
+ else resolve(newToken);
+ });
+ return;
}
- // Create the metadata for the file
- const folderId = await findOrCreateScreenityFolder(token);
- const fileMetadata = {
- name: fileName,
- parents: [folderId],
- };
-
- // Update the file metadata with the name
- const metadataResponse = await fetch(
- `https://www.googleapis.com/drive/v3/files/${fileId}`,
- {
- method: "PATCH",
- headers: new Headers({
- Authorization: `Bearer ${token}`,
- "Content-Type": "application/json; charset=UTF-8",
- }),
- body: JSON.stringify(fileMetadata),
- }
- );
-
- if (!metadataResponse.ok) {
- const errorResponse = await metadataResponse.json();
- console.error(
- "Error updating file metadata:",
- metadataResponse.status,
- errorResponse.error.message
- );
- throw new Error(
- `Error updating file metadata: ${metadataResponse.status}`
- );
+ const exp = payload.exp * 1000;
+ if (Date.now() >= exp) {
+ chrome.identity.getAuthToken({ interactive: true }, (newToken) => {
+ if (chrome.runtime.lastError)
+ reject(new Error(chrome.runtime.lastError));
+ else resolve(newToken);
+ });
+ } else {
+ resolve(token);
}
- sendResponse({ status: "ok", url: fileId });
-
- // Open the Google Drive file in a new tab
- chrome.tabs.create({
- url: `https://drive.google.com/file/d/${fileId}/view`,
- });
-
- resolve(`https://drive.google.com/file/d/${fileId}/view`); // Return the file ID if needed
- } catch (error) {
- console.error("Error uploading to Google Drive:", error.message);
- sendResponse({ status: "ew", url: null });
- reject(error);
- }
+ });
});
};
+const saveToDrive = async (videoBlob, fileName) => {
+ try {
+ const token = await getAuthTokenFromStorage();
+ if (!token) throw new Error("Sign-in failed");
+
+ // Upload the raw media
+ const uploadResponse = await fetch(
+ "https://www.googleapis.com/upload/drive/v3/files?uploadType=media",
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": videoBlob.type,
+ },
+ body: videoBlob,
+ }
+ );
+
+ if (!uploadResponse.ok)
+ throw new Error(`Upload failed: ${uploadResponse.status}`);
+
+ const { id: fileId } = await uploadResponse.json();
+ if (!fileId) throw new Error("File ID is undefined");
+
+ // Add metadata and move to folder
+ const folderId = await findOrCreateScreenityFolder(token);
+ const metadataResponse = await fetch(
+ `https://www.googleapis.com/drive/v3/files/${fileId}`,
+ {
+ method: "PATCH",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json; charset=UTF-8",
+ },
+ body: JSON.stringify({
+ name: fileName,
+ parents: [folderId],
+ }),
+ }
+ );
+
+ if (!metadataResponse.ok)
+ throw new Error(`Metadata update failed: ${metadataResponse.status}`);
+
+ // Open the file in Drive
+ chrome.tabs.create({
+ url: `https://drive.google.com/file/d/${fileId}/view`,
+ });
+
+ return { status: "ok", url: fileId };
+ } catch (error) {
+ console.error("Error uploading to Google Drive:", error.message);
+ return { status: "ew", url: null };
+ }
+};
+
const savedToDrive = async () => {
const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);
sendMessageTab(sandboxTab, { type: "saved-to-drive" });
};
-export const handleSaveToDrive = async (
- sendResponse,
- request,
- fallback = false
-) => {
- if (!fallback) {
- const blob = base64ToUint8Array(request.base64);
-
- const fileName = request.title + ".mp4";
-
- saveToDrive(blob, fileName, sendResponse).then(() => {
- savedToDrive();
- });
- } else {
- const chunks = [];
- await chunksStore.iterate((value, key) => {
- chunks.push(value);
- });
-
- // Build the video from chunks
- let array = [];
- let lastTimestamp = 0;
- for (const chunk of chunks) {
- // Check if chunk timestamp is smaller than last timestamp, if so, skip
- if (chunk.timestamp < lastTimestamp) {
- continue;
+export const handleSaveToDrive = async (request, fallback = false) => {
+ try {
+ let response;
+
+ if (!fallback) {
+ const blob = base64ToUint8Array(request.base64);
+ const fileName = request.title + ".mp4";
+ response = await saveToDrive(blob, fileName);
+ } else {
+ const chunks = [];
+ await chunksStore.iterate((value) => chunks.push(value));
+
+ let array = [];
+ let lastTimestamp = 0;
+ for (const chunk of chunks) {
+ if (chunk.timestamp < lastTimestamp) continue;
+ lastTimestamp = chunk.timestamp;
+ array.push(chunk.chunk);
}
- lastTimestamp = chunk.timestamp;
- array.push(chunk.chunk);
- }
- const blob = new Blob(array, { type: "video/webm" });
- const filename = request.title + ".webm";
+ const blob = new Blob(array, { type: "video/webm" });
+ const fileName = request.title + ".webm";
+ response = await saveToDrive(blob, fileName);
+ }
- saveToDrive(blob, filename, sendResponse).then(() => {
- savedToDrive();
- });
+ await savedToDrive();
+ return response;
+ } catch (err) {
+ console.error("handleSaveToDrive failed:", err);
+ return { status: "ew", url: null };
}
};
diff --git a/src/pages/Camera/utils/cameraUtils.js b/src/pages/Camera/utils/cameraUtils.js
index c42a574..4a493c3 100644
--- a/src/pages/Camera/utils/cameraUtils.js
+++ b/src/pages/Camera/utils/cameraUtils.js
@@ -181,7 +181,7 @@ export const surfaceHandler = async (request, videoRef) => {
const shouldEnterPip =
(request.surface === "monitor" && (!isSubscribed || instantMode)) ||
- (request.surface !== "monitor" && (isSubscribed || instantMode));
+ (request.surface !== "monitor" && isSubscribed && !instantMode);
if (shouldEnterPip && videoRef.current) {
await videoRef.current.requestPictureInPicture();