MediaWiki:CopyEmbeddedStory.js

From The Seven Sages of Rome
Revision as of 12:37, 13 March 2025 by Noeth (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
$(document).ready(function() {
  // Trigger modal when the button is clicked
  $('#copyEmbeddedStories').click(function() {
    $('#storyModal').modal('show');
    $('#autocomplete-list').empty().hide(); // Hide autocomplete list when modal opens
  });

  // Handle autocomplete for page names
  $('#page-name').on('input', function() {
    var query = $(this).val();
    if (query.length > 2) {
      $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
          action: 'query',
          list: 'allpages',
          apprefix: query,
          format: 'json',
          aplimit: 10  // Limit to 10 results for performance
        },
        success: function(response) {
          var pages = response.query.allpages;
          var suggestions = pages.map(function(page) {
            return page.title;
          });

          // Display suggestions in the dropdown
          if (suggestions.length > 0) {
            var list = $('#autocomplete-list');
            list.empty().show();
            suggestions.forEach(function(title) {
              list.append('<li class="list-group-item" style="cursor:pointer;">' + title + '</li>');
            });

            // Handle selection of a suggestion
            $('#autocomplete-list li').on('click', function() {
              $('#page-name').val($(this).text());  // Fill the input with the selected suggestion
              $('#autocomplete-list').empty().hide();  // Hide the dropdown
            });
          } else {
            $('#autocomplete-list').empty().hide();  // Hide the dropdown if no suggestions
          }
        }
      });
    } else {
      $('#autocomplete-list').empty().hide();  // Hide the dropdown if the query is too short
    }
  });

  // Hide the autocomplete list when clicking outside
  $(document).on('click', function(e) {
    if (!$(e.target).closest('#page-name').length) {
      $('#autocomplete-list').empty().hide();  // Hide the dropdown when clicking outside the input
    }
  });

  // Process the data when the "Process" button is clicked
  $('#process').click(function() {
    var targetPage = $('#page-name').val();
    if (targetPage) {
      copyEmbeddedStories(targetPage);
    }
    $('#storyModal').modal('hide');  // Close the modal
  });
});

function copyEmbeddedStories(targetPage) {
  var pageTitle = mw.config.get('wgPageName');  // Get the current page title
  
  // Step 1: Fetch the edit token
  $.ajax({
    url: mw.util.wikiScript('api'),
    data: {
      action: 'query',
      format: 'json',
      titles: pageTitle,
      meta: 'tokens',  // Request tokens for the current user
    },
    success: function(response) {
      var editToken = response.query.tokens.csrftoken;  // Get the edit token
      
      if (!editToken) {
        console.error('Failed to retrieve edit token.');
        return;
      }

      // Step 2: Get the latest revision content of the current page
      $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
          action: 'query',
          format: 'json',
          titles: pageTitle,
          prop: 'revisions',
          rvprop: 'content',  // Get only the content of the latest revision
          rvlimit: 1  // Only the latest revision
        },
        success: function(response) {
          var pages = response.query.pages;
          var latestContent = '';
          for (var pageId in pages) {
            var page = pages[pageId];
            if (page.revisions && page.revisions.length > 0) {
              latestContent = page.revisions[0]['*'];  // Get the content of the latest revision
            }
          }

          // If no content was found, log and exit
          if (!latestContent) {
            console.error('No content found in the latest revision.');
            return;
          }

          // Find all EmbeddedStory templates in the content
          var stories = latestContent.match(/\{\{EmbeddedStory[^}]*\}\}/g);  // Regex to match all EmbeddedStory templates
          var targetContent = stories ? stories.join('\n') : '';

          // If no stories are found, log and exit
          if (!targetContent) {
            console.error('No embedded stories found.');
            return;
          }

          // Step 3: Fetch the current content of the target page
          $.ajax({
            url: mw.util.wikiScript('api'),
            data: {
              action: 'query',
              format: 'json',
              titles: targetPage,
              prop: 'revisions',
              rvprop: 'content',  // Get only the content of the target page
              rvlimit: 1  // Only the latest revision
            },
            success: function(response) {
              var targetPages = response.query.pages;
              var targetPageContent = '';
              for (var targetPageId in targetPages) {
                var targetPageData = targetPages[targetPageId];
                if (targetPageData.revisions && targetPageData.revisions.length > 0) {
                  targetPageContent = targetPageData.revisions[0]['*'];  // Get the current content of the target page
                }
              }

              // Step 4: Remove any existing EmbeddedStory templates from the target page content
              var cleanedTargetContent = targetPageContent.replace(/\{\{EmbeddedStory[^}]*\}\}/g, '');

              // Step 5: Append the new embedded stories to the cleaned target page content
              var updatedContent = cleanedTargetContent + '\n' + targetContent;

              // Step 6: Use the MediaWiki API to update the target page with the new content
              $.ajax({
                url: mw.util.wikiScript('api'),
                method: 'POST',
                data: {
                  action: 'edit',
                  title: targetPage,
                  text: updatedContent,
                  summary: 'Replacing embedded stories',
                  token: editToken,  // Pass the correct edit token
                  format: 'json'
                },
                success: function(response) {
                  if (response.error) {
                    console.error('API Error:', response.error);
                    alert('Failed to copy Embedded Stories. API Error: ' + response.error.info);
                  } else {
                    alert('Embedded Stories copied and appended successfully!');
                  }
                },
                error: function(xhr, status, error) {
                  console.error('AJAX Error:', status, error);
                  alert('An error occurred while copying Embedded Stories. Please try again.');
                }
              });
            },
            error: function(xhr, status, error) {
              console.error('AJAX Error:', status, error);
              alert('Failed to fetch target page content. Please try again.');
            }
          });
        },
        error: function(xhr, status, error) {
          console.error('AJAX Error:', status, error);
          alert('Failed to fetch the latest revision. Please try again.');
        }
      });
    },
    error: function(xhr, status, error) {
      console.error('Failed to fetch edit token:', status, error);
      alert('Failed to fetch edit token. Please try again.');
    }
  });
}