User:Acagastya/startArchiving.js

From Wikinews, the free news source you can write!
Jump to navigation Jump to search

Note: After saving, you may have to bypass your browser's cache to see the changes. Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac); IE: hold Ctrl while clicking Refresh, or press Ctrl-F5; Konqueror: simply click the Reload button, or press F5; Opera users may need to completely clear their cache in Tools→Preferences. — More skins

//<nowiki>
function archiving() {
  const sourceTemplate = document.getElementsByClassName('sourceTemplate'); // get list of all <span> which uses {{source}}
  const sourceTemplateArr = [...sourceTemplate]; // convert HTMLCollection to array
  const urlArr = sourceTemplateArr.map(
    src => [...src.children] // convert HTMLCollection of <span> children to array
      .filter(el => el.tagName == 'A') // discard <span> children which are not <a>
  )
    .flat() // flatten the array (eg: Reuters. "Lorem Ipsum Dolor Sit Amet" -- Foo Bar)
    .filter(link => !link.hostname.includes('en.wikinews.org')) // discard pub links
    .map(link => link.href) // extract href
    ;
  urlArr.forEach(archiveUrl);
}

function archiveUrl(url) {
  const completeUrl = `https://web.archive.org/save/${url}`;
  const win = window.open(completeUrl, '_blank');
  win.focus()
}

function saInit() {
  if(mw.config.get('wgNamespaceNumber') != 0) return;
  let t = document.getElementById('p-article-tools');
  if (!t) return;
  let li = document.createElement('li');
  let a = document.createElement('a');
  a.setAttribute('href', 'javascript:startArchiving.archiving()');
  a.setAttribute('id', 'start-archiving');
  a.innerText = 'Start archiving';
  li.setAttribute('id', 'ca-startarchiving');
  li.appendChild(a);

  const tBody = [...t.children][1];
  const ul = [...tBody.children][0];
  ul.appendChild(li);
}

const startArchiving = {
  archiving,
  saInit
};

$.when(mw.loader.using(['mediawiki.util']), $.ready).done(startArchiving.saInit);
//</nowiki>