Commit d1311178 authored by Stefy Spora's avatar Stefy Spora

Fix story-data retrieval by fetching raw HTML from GET request

- Update getCurrentMediaData function in content.js to fetch raw HTML from current page URL
- Parse story-data script tag from raw HTML response instead of relying on DOM
- Update background.js executePrivacyUpdateFromContext to use same approach
- Handle cases where story-data script is removed by JavaScript after page load
- Add proper error handling and fallback to default values
- Maintain existing functionality while fixing story-data retrieval issue
- Update bulk processing functions to use new story-data retrieval method
parent 8eea4178
...@@ -347,7 +347,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -347,7 +347,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
throw new Error('Could not find CSRF token. Please refresh the page and try again.'); throw new Error('Could not find CSRF token. Please refresh the page and try again.');
} }
// Step 3: Parse story-data script tag to get current media data // Step 3: Fetch raw HTML and parse story-data
let currentData = { let currentData = {
title: '', title: '',
caption: '', caption: '',
...@@ -357,23 +357,52 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -357,23 +357,52 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
}; };
try { try {
const storyDataScript = document.getElementById('story-data') || document.querySelector('script[id="story-data"]'); console.log('Fetching raw HTML to get story-data...');
if (storyDataScript) { // Fetch the raw HTML of the current page to get the story-data script
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML; const response = await fetch(window.location.href, {
method: 'GET',
credentials: 'same-origin',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Cache-Control': 'no-cache'
}
});
if (!response.ok) {
throw new Error(`Failed to fetch page HTML: ${response.status}`);
}
const htmlText = await response.text();
console.log('Fetched raw HTML, parsing for story-data...');
// Parse the story-data from the raw HTML
const storyDataMatch = htmlText.match(/<script[^>]*id=["']story-data["'][^>]*>([\s\S]*?)<\/script>/i);
if (storyDataMatch && storyDataMatch[1]) {
const scriptContent = storyDataMatch[1].trim();
console.log('Found story-data script content:', scriptContent.substring(0, 200) + '...');
if (scriptContent) {
let storyData; let storyData;
// Try to parse as JSON directly first
try {
storyData = JSON.parse(scriptContent);
} catch (directParseError) {
// If direct parsing fails, look for JSON within the script content
const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/); const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/);
if (jsonMatch) { if (jsonMatch) {
storyData = JSON.parse(jsonMatch[1]); storyData = JSON.parse(jsonMatch[1]);
} else { } else {
storyData = JSON.parse(scriptContent); throw new Error('Could not find JSON in story-data script');
} }
}
console.log('Parsed story-data:', storyData);
// Extract data from attributes based on media type // Extract data from attributes based on media type
if (storyData.attributes) { if (storyData.attributes) {
const attributes = storyData.attributes; const attributes = storyData.attributes;
console.log('Found attributes in story-data:', attributes);
// Try to extract from pictures first // Try to extract from pictures first
if (attributes.pictures && attributes.pictures.length > 0) { if (attributes.pictures && attributes.pictures.length > 0) {
...@@ -385,6 +414,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -385,6 +414,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: picture.tags_names || picture.tags || [], tag_names: picture.tags_names || picture.tags || [],
user_tag_ids: picture.user_tags_ids || picture.userTags || [] user_tag_ids: picture.user_tags_ids || picture.userTags || []
}; };
console.log('Extracted picture data from story-data:', currentData);
} }
// Try to extract from videos // Try to extract from videos
else if (attributes.videos && attributes.videos.length > 0) { else if (attributes.videos && attributes.videos.length > 0) {
...@@ -396,6 +426,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -396,6 +426,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: video.tags_names || video.tags || [], tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || [] user_tag_ids: video.user_tags_ids || video.userTags || []
}; };
console.log('Extracted video data from story-data:', currentData);
} }
// Fallback to direct attributes // Fallback to direct attributes
else { else {
...@@ -406,6 +437,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -406,6 +437,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: attributes.tags_names || attributes.tags || [], tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: attributes.user_tags_ids || attributes.userTags || [] user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
}; };
console.log('Extracted direct attributes from story-data:', currentData);
} }
} }
// Fallback to root level data // Fallback to root level data
...@@ -417,11 +449,13 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -417,11 +449,13 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: storyData.tags_names || storyData.tags || [], tag_names: storyData.tags_names || storyData.tags || [],
user_tag_ids: storyData.user_tags_ids || storyData.userTags || [] user_tag_ids: storyData.user_tags_ids || storyData.userTags || []
}; };
console.log('Extracted root level data from story-data:', currentData);
} }
} } else {
console.warn('story-data script tag not found in raw HTML');
} }
} catch (error) { } catch (error) {
console.warn('Could not parse story data, using defaults:', error); console.warn('Could not fetch or parse story-data from raw HTML, using defaults:', error);
} }
// Step 4: Prepare payload based on media type and privacy level // Step 4: Prepare payload based on media type and privacy level
...@@ -529,6 +563,7 @@ function executeBulkPrivacyUpdateFromContext() { ...@@ -529,6 +563,7 @@ function executeBulkPrivacyUpdateFromContext() {
async function updateMediaPrivacyById(mediaType, mediaId, csrfToken, privacyLevel = 'friends_only') { async function updateMediaPrivacyById(mediaType, mediaId, csrfToken, privacyLevel = 'friends_only') {
try { try {
// For bulk processing, we use default values since we don't have access to individual page data // For bulk processing, we use default values since we don't have access to individual page data
// This is a simplified version that doesn't fetch current data for performance
let payload; let payload;
if (mediaType === 'video') { if (mediaType === 'video') {
payload = { payload = {
...@@ -569,7 +604,7 @@ function executeBulkPrivacyUpdateFromContext() { ...@@ -569,7 +604,7 @@ function executeBulkPrivacyUpdateFromContext() {
throw new Error(`XHR request failed: ${response.status} ${response.statusText}`); throw new Error(`XHR request failed: ${response.status} ${response.statusText}`);
} }
return { success: true, message: `${mediaType} ${mediaId} updated successfully` }; return { success: true, message: `${mediaType} ${mediaId} updated to "${privacyLevel === 'friends_only' ? 'friends only' : 'all fetlifers'}" successfully` };
} catch (error) { } catch (error) {
console.error(`Failed to update ${mediaType} ${mediaId}:`, error); console.error(`Failed to update ${mediaType} ${mediaId}:`, error);
......
...@@ -58,77 +58,69 @@ ...@@ -58,77 +58,69 @@
return null; return null;
} }
// Function to get current media data by parsing the story-data script tag // Function to get current media data by fetching raw HTML and parsing story-data
function getCurrentMediaData() { async function getCurrentMediaData() {
try { try {
// Find the script tag with id "story-data" console.log('Fetching raw HTML to get story-data...');
const storyDataScript = document.getElementById('story-data') || document.querySelector('script[id="story-data"]');
if (!storyDataScript) { // Fetch the raw HTML of the current page to get the story-data script
console.warn('Story data script not found, using defaults'); const response = await fetch(window.location.href, {
return { method: 'GET',
title: '', credentials: 'same-origin',
caption: '', headers: {
description: '', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
tag_names: [], 'Cache-Control': 'no-cache'
user_tag_ids: []
};
} }
});
// Extract the JSON content from the script tag if (!response.ok) {
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML; throw new Error(`Failed to fetch page HTML: ${response.status}`);
}
if (!scriptContent) { const htmlText = await response.text();
console.warn('Story data script is empty, using defaults'); console.log('Fetched raw HTML, parsing for story-data...');
return {
// Parse the story-data from the raw HTML
let mediaData = {
title: '', title: '',
caption: '', caption: '',
description: '', description: '',
tag_names: [], tag_names: [],
user_tag_ids: [] user_tag_ids: []
}; };
}
// Parse the JSON data try {
// Look for the story-data script tag in the raw HTML
const storyDataMatch = htmlText.match(/<script[^>]*id=["']story-data["'][^>]*>([\s\S]*?)<\/script>/i);
if (storyDataMatch && storyDataMatch[1]) {
const scriptContent = storyDataMatch[1].trim();
console.log('Found story-data script content:', scriptContent.substring(0, 200) + '...');
let storyData; let storyData;
// Try to parse as JSON directly first
try { try {
// The script content might be wrapped in a JavaScript assignment storyData = JSON.parse(scriptContent);
// Try to extract just the JSON part } catch (directParseError) {
// If direct parsing fails, look for JSON within the script content
const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/); const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/);
if (jsonMatch) { if (jsonMatch) {
storyData = JSON.parse(jsonMatch[1]); storyData = JSON.parse(jsonMatch[1]);
} else { } else {
storyData = JSON.parse(scriptContent); throw new Error('Could not find JSON in story-data script');
} }
} catch (parseError) {
console.warn('Failed to parse story data JSON:', parseError);
return {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
} }
console.log('Parsed story data:', storyData); console.log('Parsed story-data:', storyData);
// Extract data from attributes based on media type // Extract data from attributes based on media type
let mediaData = {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
// Check if we have attributes and can extract media data
if (storyData.attributes) { if (storyData.attributes) {
const attributes = storyData.attributes; const attributes = storyData.attributes;
console.log('Found attributes in story-data:', attributes);
// Try to extract from pictures first // Try to extract from pictures first
if (attributes.pictures && attributes.pictures.length > 0) { if (attributes.pictures && attributes.pictures.length > 0) {
const picture = attributes.pictures[0]; // Get first picture const picture = attributes.pictures[0];
mediaData = { mediaData = {
title: picture.title || '', title: picture.title || '',
caption: picture.caption || '', caption: picture.caption || '',
...@@ -136,11 +128,11 @@ ...@@ -136,11 +128,11 @@
tag_names: picture.tags_names || picture.tags || [], tag_names: picture.tags_names || picture.tags || [],
user_tag_ids: picture.user_tags_ids || picture.userTags || [] user_tag_ids: picture.user_tags_ids || picture.userTags || []
}; };
console.log('Extracted picture data from attributes:', mediaData); console.log('Extracted picture data from story-data:', mediaData);
} }
// Try to extract from videos // Try to extract from videos
else if (attributes.videos && attributes.videos.length > 0) { else if (attributes.videos && attributes.videos.length > 0) {
const video = attributes.videos[0]; // Get first video const video = attributes.videos[0];
mediaData = { mediaData = {
title: video.title || '', title: video.title || '',
caption: '', // Videos don't have caption caption: '', // Videos don't have caption
...@@ -148,7 +140,7 @@ ...@@ -148,7 +140,7 @@
tag_names: video.tags_names || video.tags || [], tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || [] user_tag_ids: video.user_tags_ids || video.userTags || []
}; };
console.log('Extracted video data from attributes:', mediaData); console.log('Extracted video data from story-data:', mediaData);
} }
// Fallback to direct attributes // Fallback to direct attributes
else { else {
...@@ -159,7 +151,7 @@ ...@@ -159,7 +151,7 @@
tag_names: attributes.tags_names || attributes.tags || [], tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: attributes.user_tags_ids || attributes.userTags || [] user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
}; };
console.log('Extracted data from direct attributes:', mediaData); console.log('Extracted direct attributes from story-data:', mediaData);
} }
} }
// Fallback to root level data // Fallback to root level data
...@@ -171,13 +163,20 @@ ...@@ -171,13 +163,20 @@
tag_names: storyData.tags_names || storyData.tags || [], tag_names: storyData.tags_names || storyData.tags || [],
user_tag_ids: storyData.user_tags_ids || storyData.userTags || [] user_tag_ids: storyData.user_tags_ids || storyData.userTags || []
}; };
console.log('Extracted data from root level:', mediaData); console.log('Extracted root level data from story-data:', mediaData);
}
} else {
console.warn('story-data script tag not found in raw HTML');
}
} catch (parseError) {
console.warn('Could not parse story-data from raw HTML, using defaults:', parseError);
} }
console.log('Final extracted data:', mediaData);
return mediaData; return mediaData;
} catch (error) { } catch (error) {
console.warn('Could not parse current media data, using defaults:', error); console.warn('Could not fetch or parse current media data, using defaults:', error);
return { return {
title: '', title: '',
caption: '', caption: '',
...@@ -208,7 +207,7 @@ ...@@ -208,7 +207,7 @@
} }
// Step 3: Get current media data to preserve existing values // Step 3: Get current media data to preserve existing values
const currentData = getCurrentMediaData(); const currentData = await getCurrentMediaData();
// Step 4: Prepare payload based on media type and privacy level // Step 4: Prepare payload based on media type and privacy level
let payload; let payload;
...@@ -259,7 +258,7 @@ ...@@ -259,7 +258,7 @@
return { return {
success: true, success: true,
message: `${mediaInfo.type.charAt(0).toUpperCase() + mediaInfo.type.slice(1)} privacy updated to "only friends" successfully!` message: `${mediaInfo.type.charAt(0).toUpperCase() + mediaInfo.type.slice(1)} privacy updated to "${privacyLevel === 'friends_only' ? 'friends only' : 'all fetlifers'}" successfully!`
}; };
} catch (error) { } catch (error) {
...@@ -294,7 +293,7 @@ ...@@ -294,7 +293,7 @@
} }
// Function to update privacy for a specific media item by ID // Function to update privacy for a specific media item by ID
async function updateMediaPrivacyById(mediaType, mediaId) { async function updateMediaPrivacyById(mediaType, mediaId, privacyLevel = 'friends_only') {
try { try {
// Get CSRF token // Get CSRF token
const csrfToken = getCSRFToken(); const csrfToken = getCSRFToken();
...@@ -302,29 +301,27 @@ ...@@ -302,29 +301,27 @@
throw new Error('Could not find CSRF token'); throw new Error('Could not find CSRF token');
} }
// Get current media data // For bulk processing, we use default values since we don't have access to individual page data
const currentData = getCurrentMediaData(); // This is a simplified version that doesn't fetch current data for performance
// Prepare payload
let payload; let payload;
if (mediaType === 'video') { if (mediaType === 'video') {
payload = { payload = {
video: { video: {
title: currentData.title, title: "",
description: currentData.description, description: "",
only_friends: true, only_friends: privacyLevel === 'friends_only' ? true : false,
tag_names: currentData.tag_names, tag_names: [],
user_tag_ids: currentData.user_tag_ids user_tag_ids: []
}, },
render_flash: true render_flash: true
}; };
} else { } else {
payload = { payload = {
picture: { picture: {
caption: currentData.caption, caption: "",
content_privacy: "only_friends", content_privacy: privacyLevel === 'friends_only' ? "only_friends" : "public",
tag_names: currentData.tag_names, tag_names: [],
user_tag_ids: currentData.user_tag_ids user_tag_ids: []
}, },
render_flash: true render_flash: true
}; };
...@@ -347,7 +344,7 @@ ...@@ -347,7 +344,7 @@
throw new Error(`XHR request failed: ${response.status} ${response.statusText}`); throw new Error(`XHR request failed: ${response.status} ${response.statusText}`);
} }
return { success: true, message: `${mediaType} ${mediaId} updated successfully` }; return { success: true, message: `${mediaType} ${mediaId} updated to "${privacyLevel === 'friends_only' ? 'friends only' : 'all fetlifers'}" successfully` };
} catch (error) { } catch (error) {
console.error(`Failed to update ${mediaType} ${mediaId}:`, error); console.error(`Failed to update ${mediaType} ${mediaId}:`, error);
...@@ -414,7 +411,7 @@ ...@@ -414,7 +411,7 @@
// Process all media items on current page // Process all media items on current page
for (const item of mediaItems) { for (const item of mediaItems) {
try { try {
const result = await updateMediaPrivacyById(item.type, item.id); const result = await updateMediaPrivacyById(item.type, item.id, 'friends_only');
if (result.success) { if (result.success) {
successCount++; successCount++;
} else { } else {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment