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,71 +357,105 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') { ...@@ -357,71 +357,105 @@ 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...');
// Fetch the raw HTML of the current page to get the story-data script
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...');
if (storyDataScript) { // Parse the story-data from the raw HTML
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML; const storyDataMatch = htmlText.match(/<script[^>]*id=["']story-data["'][^>]*>([\s\S]*?)<\/script>/i);
if (scriptContent) { if (storyDataMatch && storyDataMatch[1]) {
let storyData; const scriptContent = storyDataMatch[1].trim();
console.log('Found story-data script content:', scriptContent.substring(0, 200) + '...');
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');
} }
}
// Extract data from attributes based on media type console.log('Parsed story-data:', storyData);
if (storyData.attributes) {
const attributes = storyData.attributes; // Extract data from attributes based on media type
if (storyData.attributes) {
// Try to extract from pictures first const attributes = storyData.attributes;
if (attributes.pictures && attributes.pictures.length > 0) { console.log('Found attributes in story-data:', attributes);
const picture = attributes.pictures[0];
currentData = { // Try to extract from pictures first
title: picture.title || '', if (attributes.pictures && attributes.pictures.length > 0) {
caption: picture.caption || '', const picture = attributes.pictures[0];
description: picture.description || picture.caption || '', currentData = {
tag_names: picture.tags_names || picture.tags || [], title: picture.title || '',
user_tag_ids: picture.user_tags_ids || picture.userTags || [] caption: picture.caption || '',
}; description: picture.description || picture.caption || '',
} tag_names: picture.tags_names || picture.tags || [],
// Try to extract from videos user_tag_ids: picture.user_tags_ids || picture.userTags || []
else if (attributes.videos && attributes.videos.length > 0) { };
const video = attributes.videos[0]; console.log('Extracted picture data from story-data:', currentData);
currentData = {
title: video.title || '',
caption: '', // Videos don't have caption
description: video.description || '',
tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || []
};
}
// Fallback to direct attributes
else {
currentData = {
title: attributes.title || attributes.name || '',
caption: attributes.caption || '',
description: attributes.description || attributes.caption || '',
tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
};
}
} }
// Fallback to root level data // Try to extract from videos
else if (attributes.videos && attributes.videos.length > 0) {
const video = attributes.videos[0];
currentData = {
title: video.title || '',
caption: '', // Videos don't have caption
description: video.description || '',
tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || []
};
console.log('Extracted video data from story-data:', currentData);
}
// Fallback to direct attributes
else { else {
currentData = { currentData = {
title: storyData.title || storyData.name || '', title: attributes.title || attributes.name || '',
caption: storyData.caption || '', caption: attributes.caption || '',
description: storyData.description || storyData.caption || '', description: attributes.description || attributes.caption || '',
tag_names: storyData.tags_names || storyData.tags || [], tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: storyData.user_tags_ids || storyData.userTags || [] user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
}; };
console.log('Extracted direct attributes from story-data:', currentData);
} }
} }
// Fallback to root level data
else {
currentData = {
title: storyData.title || storyData.name || '',
caption: storyData.caption || '',
description: storyData.description || storyData.caption || '',
tag_names: storyData.tags_names || storyData.tags || [],
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,62 +58,29 @@ ...@@ -58,62 +58,29 @@
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) {
console.warn('Story data script not found, using defaults');
return {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
}
// Extract the JSON content from the script tag
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML;
if (!scriptContent) {
console.warn('Story data script is empty, using defaults');
return {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
}
// Parse the JSON data // Fetch the raw HTML of the current page to get the story-data script
let storyData; const response = await fetch(window.location.href, {
try { method: 'GET',
// The script content might be wrapped in a JavaScript assignment credentials: 'same-origin',
// Try to extract just the JSON part headers: {
const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/); 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
if (jsonMatch) { 'Cache-Control': 'no-cache'
storyData = JSON.parse(jsonMatch[1]);
} else {
storyData = JSON.parse(scriptContent);
} }
} catch (parseError) { });
console.warn('Failed to parse story data JSON:', parseError);
return { if (!response.ok) {
title: '', throw new Error(`Failed to fetch page HTML: ${response.status}`);
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
} }
console.log('Parsed story data:', storyData); const htmlText = await response.text();
console.log('Fetched raw HTML, parsing for story-data...');
// Extract data from attributes based on media type // Parse the story-data from the raw HTML
let mediaData = { let mediaData = {
title: '', title: '',
caption: '', caption: '',
...@@ -122,62 +89,94 @@ ...@@ -122,62 +89,94 @@
user_tag_ids: [] user_tag_ids: []
}; };
// Check if we have attributes and can extract media data try {
if (storyData.attributes) { // Look for the story-data script tag in the raw HTML
const attributes = storyData.attributes; const storyDataMatch = htmlText.match(/<script[^>]*id=["']story-data["'][^>]*>([\s\S]*?)<\/script>/i);
// Try to extract from pictures first if (storyDataMatch && storyDataMatch[1]) {
if (attributes.pictures && attributes.pictures.length > 0) { const scriptContent = storyDataMatch[1].trim();
const picture = attributes.pictures[0]; // Get first picture console.log('Found story-data script content:', scriptContent.substring(0, 200) + '...');
mediaData = {
title: picture.title || '', let storyData;
caption: picture.caption || '', // Try to parse as JSON directly first
description: picture.description || picture.caption || '', try {
tag_names: picture.tags_names || picture.tags || [], storyData = JSON.parse(scriptContent);
user_tag_ids: picture.user_tags_ids || picture.userTags || [] } catch (directParseError) {
}; // If direct parsing fails, look for JSON within the script content
console.log('Extracted picture data from attributes:', mediaData); const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/);
} if (jsonMatch) {
// Try to extract from videos storyData = JSON.parse(jsonMatch[1]);
else if (attributes.videos && attributes.videos.length > 0) { } else {
const video = attributes.videos[0]; // Get first video throw new Error('Could not find JSON in story-data script');
mediaData = { }
title: video.title || '', }
caption: '', // Videos don't have caption
description: video.description || '', console.log('Parsed story-data:', storyData);
tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || [] // Extract data from attributes based on media type
}; if (storyData.attributes) {
console.log('Extracted video data from attributes:', mediaData); const attributes = storyData.attributes;
} console.log('Found attributes in story-data:', attributes);
// Fallback to direct attributes
else { // Try to extract from pictures first
mediaData = { if (attributes.pictures && attributes.pictures.length > 0) {
title: attributes.title || attributes.name || '', const picture = attributes.pictures[0];
caption: attributes.caption || '', mediaData = {
description: attributes.description || attributes.caption || '', title: picture.title || '',
tag_names: attributes.tags_names || attributes.tags || [], caption: picture.caption || '',
user_tag_ids: attributes.user_tags_ids || attributes.userTags || [] description: picture.description || picture.caption || '',
}; tag_names: picture.tags_names || picture.tags || [],
console.log('Extracted data from direct attributes:', mediaData); user_tag_ids: picture.user_tags_ids || picture.userTags || []
};
console.log('Extracted picture data from story-data:', mediaData);
}
// Try to extract from videos
else if (attributes.videos && attributes.videos.length > 0) {
const video = attributes.videos[0];
mediaData = {
title: video.title || '',
caption: '', // Videos don't have caption
description: video.description || '',
tag_names: video.tags_names || video.tags || [],
user_tag_ids: video.user_tags_ids || video.userTags || []
};
console.log('Extracted video data from story-data:', mediaData);
}
// Fallback to direct attributes
else {
mediaData = {
title: attributes.title || attributes.name || '',
caption: attributes.caption || '',
description: attributes.description || attributes.caption || '',
tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
};
console.log('Extracted direct attributes from story-data:', mediaData);
}
}
// Fallback to root level data
else {
mediaData = {
title: storyData.title || storyData.name || '',
caption: storyData.caption || '',
description: storyData.description || storyData.caption || '',
tag_names: storyData.tags_names || storyData.tags || [],
user_tag_ids: storyData.user_tags_ids || storyData.userTags || []
};
console.log('Extracted root level data from story-data:', mediaData);
}
} else {
console.warn('story-data script tag not found in raw HTML');
} }
} } catch (parseError) {
// Fallback to root level data console.warn('Could not parse story-data from raw HTML, using defaults:', parseError);
else {
mediaData = {
title: storyData.title || storyData.name || '',
caption: storyData.caption || '',
description: storyData.description || storyData.caption || '',
tag_names: storyData.tags_names || storyData.tags || [],
user_tag_ids: storyData.user_tags_ids || storyData.userTags || []
};
console.log('Extracted data from root level:', mediaData);
} }
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