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') {
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 = {
title: '',
caption: '',
......@@ -357,23 +357,52 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
};
try {
const storyDataScript = document.getElementById('story-data') || document.querySelector('script[id="story-data"]');
console.log('Fetching raw HTML to get story-data...');
if (storyDataScript) {
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML;
// 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...');
// 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;
// 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]*\})/);
if (jsonMatch) {
storyData = JSON.parse(jsonMatch[1]);
} 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
if (storyData.attributes) {
const attributes = storyData.attributes;
console.log('Found attributes in story-data:', attributes);
// Try to extract from pictures first
if (attributes.pictures && attributes.pictures.length > 0) {
......@@ -385,6 +414,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: picture.tags_names || picture.tags || [],
user_tag_ids: picture.user_tags_ids || picture.userTags || []
};
console.log('Extracted picture data from story-data:', currentData);
}
// Try to extract from videos
else if (attributes.videos && attributes.videos.length > 0) {
......@@ -396,6 +426,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
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 {
......@@ -406,6 +437,7 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
tag_names: attributes.tags_names || attributes.tags || [],
user_tag_ids: attributes.user_tags_ids || attributes.userTags || []
};
console.log('Extracted direct attributes from story-data:', currentData);
}
}
// Fallback to root level data
......@@ -417,11 +449,13 @@ function executePrivacyUpdateFromContext(privacyLevel = 'friends_only') {
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) {
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
......@@ -529,6 +563,7 @@ function executeBulkPrivacyUpdateFromContext() {
async function updateMediaPrivacyById(mediaType, mediaId, csrfToken, privacyLevel = 'friends_only') {
try {
// 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;
if (mediaType === 'video') {
payload = {
......@@ -569,7 +604,7 @@ function executeBulkPrivacyUpdateFromContext() {
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) {
console.error(`Failed to update ${mediaType} ${mediaId}:`, error);
......
......@@ -58,77 +58,69 @@
return null;
}
// Function to get current media data by parsing the story-data script tag
function getCurrentMediaData() {
// Function to get current media data by fetching raw HTML and parsing story-data
async function getCurrentMediaData() {
try {
// Find the script tag with id "story-data"
const storyDataScript = document.getElementById('story-data') || document.querySelector('script[id="story-data"]');
console.log('Fetching raw HTML to get story-data...');
if (!storyDataScript) {
console.warn('Story data script not found, using defaults');
return {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
// 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'
}
});
// Extract the JSON content from the script tag
const scriptContent = storyDataScript.textContent || storyDataScript.innerHTML;
if (!response.ok) {
throw new Error(`Failed to fetch page HTML: ${response.status}`);
}
if (!scriptContent) {
console.warn('Story data script is empty, using defaults');
return {
const htmlText = await response.text();
console.log('Fetched raw HTML, parsing for story-data...');
// Parse the story-data from the raw HTML
let mediaData = {
title: '',
caption: '',
description: '',
tag_names: [],
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;
// Try to parse as JSON directly first
try {
// The script content might be wrapped in a JavaScript assignment
// Try to extract just the JSON part
storyData = JSON.parse(scriptContent);
} catch (directParseError) {
// If direct parsing fails, look for JSON within the script content
const jsonMatch = scriptContent.match(/(\{[\s\S]*\})/);
if (jsonMatch) {
storyData = JSON.parse(jsonMatch[1]);
} 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
let mediaData = {
title: '',
caption: '',
description: '',
tag_names: [],
user_tag_ids: []
};
// Check if we have attributes and can extract media data
if (storyData.attributes) {
const attributes = storyData.attributes;
console.log('Found attributes in story-data:', attributes);
// Try to extract from pictures first
if (attributes.pictures && attributes.pictures.length > 0) {
const picture = attributes.pictures[0]; // Get first picture
const picture = attributes.pictures[0];
mediaData = {
title: picture.title || '',
caption: picture.caption || '',
......@@ -136,11 +128,11 @@
tag_names: picture.tags_names || picture.tags || [],
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
else if (attributes.videos && attributes.videos.length > 0) {
const video = attributes.videos[0]; // Get first video
const video = attributes.videos[0];
mediaData = {
title: video.title || '',
caption: '', // Videos don't have caption
......@@ -148,7 +140,7 @@
tag_names: video.tags_names || video.tags || [],
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
else {
......@@ -159,7 +151,7 @@
tag_names: attributes.tags_names || attributes.tags || [],
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
......@@ -171,13 +163,20 @@
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('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;
} 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 {
title: '',
caption: '',
......@@ -208,7 +207,7 @@
}
// 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
let payload;
......@@ -259,7 +258,7 @@
return {
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) {
......@@ -294,7 +293,7 @@
}
// 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 {
// Get CSRF token
const csrfToken = getCSRFToken();
......@@ -302,29 +301,27 @@
throw new Error('Could not find CSRF token');
}
// Get current media data
const currentData = getCurrentMediaData();
// Prepare payload
// 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;
if (mediaType === 'video') {
payload = {
video: {
title: currentData.title,
description: currentData.description,
only_friends: true,
tag_names: currentData.tag_names,
user_tag_ids: currentData.user_tag_ids
title: "",
description: "",
only_friends: privacyLevel === 'friends_only' ? true : false,
tag_names: [],
user_tag_ids: []
},
render_flash: true
};
} else {
payload = {
picture: {
caption: currentData.caption,
content_privacy: "only_friends",
tag_names: currentData.tag_names,
user_tag_ids: currentData.user_tag_ids
caption: "",
content_privacy: privacyLevel === 'friends_only' ? "only_friends" : "public",
tag_names: [],
user_tag_ids: []
},
render_flash: true
};
......@@ -347,7 +344,7 @@
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) {
console.error(`Failed to update ${mediaType} ${mediaId}:`, error);
......@@ -414,7 +411,7 @@
// Process all media items on current page
for (const item of mediaItems) {
try {
const result = await updateMediaPrivacyById(item.type, item.id);
const result = await updateMediaPrivacyById(item.type, item.id, 'friends_only');
if (result.success) {
successCount++;
} 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