dvargas92495 / SmartBlocks

Useful examples from developer community for Roam42 SmartBlocks
147 stars 7 forks source link

Tweet extractor v. 1.5 #216

Open fbgallet opened 3 years ago

fbgallet commented 3 years ago

Instructions to install it: Import the JSON file below (unzip it first, of course) in your Roam dababase to be sure to preserve the code structure (copy/past doesn't work well here): Tweet author names SmartBlock v 1.5.zip

📋 Description

Making it easy to archive tweets in Roam:

Version log: v.1.5 (13 april, 2021)

v.1.4 (12 april, 2021)

v.1.3 (11 april, 2021)

v. 1.22 (10 april, 2021)

v. 1.21 (10 april, 2021)

v 1.1 (9 april, 2021)

✅ Prerequisites or dependencies that are required for this SmartBlock

Need of course Roam42 installed and running in you Roam graph.

The tweet URL has to be the last url of the block (it works of course if there is only the tweet url!)

📷 Screenshot

tweet sb code img 1

tweet sb code img 2

Extract text from tweet SmartBlock: tweet sb code img 3

💡 Additional Info

Import the JSON file below (unzip it first, of course) in your Roam dababase to be sure to preserve the code structure (copy/past doesn't work well here): Tweet author names SmartBlock v 1.5.zip

Fastest way (tweet's url in clipboard + workbench): tweet sb fastest

More complere demo: https://youtu.be/QqnD1U_j9Fw

✂️ Code of the Smartblocks:

- #42SmartBlock Tweet - extract author names & alias child block
    - <%NOBLOCKOUTPUT%> <%JA:```javascript
/* 
Version: 1.5
Published: April 13, 2021
By: Fabrice Gallet
Twitter: @fbgallet

Support my work on: https://www.buymeacoffee.com/fbgallet

************************ USER SETTINGS ************************/

let publicNameAsRef = true; // true: by [[Full public Name]] (@username), false: [[@username]] (Full public Name)
let prefixName = "@";       // "" for no change,  "@" for Ref like [[@username]] or [[@Author Name]], 
                            // (@username), when not used as reference, has always @ prefix
let withAlias = true;       // if false, no alias to tweet block-ref is added
let formatAlias = "👁‍🗨";    // icon to click for sneak peek

/* You can also disable the button to extract text, line 28
/* And change or remove the prefix text in the "Tweet - extract text" SmartBlock, line 26
/***************************************************************/

let startingBlockUID = roam42.common.currentActiveBlockUID();

/* if the block is empty, suppose that the tweet url is in the clipboard, then paste it*/
let blockContent = document.activeElement.value;
if (blockContent=="" || blockContent=="  ") { blockContent = await navigator.clipboard.readText(); }

/* Move tweet in child block and add button for extracting text */
blockContent += " {{📑:42SmartBlock:Tweet - extract text}}  "; // put '//' before this line if you want to disable this button
// the 3 lines below replace the old and unstable way to get child block ref (or uid)
await roam42.common.createBlock(startingBlockUID, -1, blockContent);
let blockInfo = await roam42.common.getBlockInfoByUID(startingBlockUID, true);
let blockRef = blockInfo[0][0].children[0].uid;

/* extract only the last URL of the block as tweet URL, in case some comments and already in the block */
let urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
function linkify(text) {
    return text.match(urlRegex);
} 
let urlTweet = blockContent;
let urlsTab = linkify(urlTweet);
urlTweet = urlsTab[urlsTab.length - 1];

/* Extract username from tweet url */
let stringArray = urlTweet.split("/",4);
var userName = stringArray[3];

/* Get Public Name with oembed JQuerie from Twitter API */
$.ajax({
        url: "https://publish.twitter.com/oembed?omit_script=1&url=" + urlTweet,
        dataType: "jsonp",
        success: function(data){
            var authorName = data.author_name;
            let authorNameTab = authorName.split(" ");
            authorName = authorNameTab[0];
            let index = 1;
            while ((index < authorNameTab.length) && !(/\W+/).test(authorNameTab[index].charAt(0))) {
              authorName += " " + authorNameTab[index];
              index++;
            }
/* Print [[Full public Name]] as reference before (@username) or the opposite according to user settings */ 
            if (publicNameAsRef) {
                PrintTitle(FormatUserName(authorName, "@" + userName, prefixName), withAlias, formatAlias, startingBlockUID, blockRef);
            } else {
                PrintTitle(FormatUserName(userName, authorName, prefixName), withAlias, formatAlias, startingBlockUID, blockRef);
            }
    }
});

function FormatUserName(nameR, nameP, prefix) {
  let names = "[[" + prefix + nameR + "]] " + "(" + nameP + ")";
  return names;
}

function PrintTitle(names, k, alias, refP, refC) {
    var title = "#tweet by " + names;
    if (k) {
        title += " [" + alias + "](((" + refC + ")))";  
    }
    roam42.common.updateBlock(refP, title, true);
}
roam42.common.moveCursorToPreviousBlock(document.activeElement);
//await roam42.common.sleep(150);
```%>
- #42SmartBlock Tweet - extract text <%HIDE%>
    - <%JA:```javascript
let urlTweet = document.activeElement.value;

/* extract only the last URL of the block as tweet URL, in case some comments and already in the block */
let urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
function linkify(text) {
    return text.match(urlRegex);
} 
let urlsTab = linkify(urlTweet);
urlTweet = urlsTab[urlsTab.length - 1];

// call Twitter API and stripe Html text (some special caracter may remain)
$.ajax({
        url: "https://publish.twitter.com/oembed?omit_script=1&url=" + urlTweet,
        dataType: "jsonp",
        success: function(data){
            let htmlString= data.html;
            var stripedHtml = htmlString.replace(/<br[^>]*>/gi, "\n");
            stripedHtml = stripedHtml.replace(/<[^>]+>/g, '');
//          stripedHtml = stripedHtml.replace(/&quot;|&#39;|&mdash;/g,' ');
            stripedHtml = stripedHtml.replace(/&quot;/g,'"');
            stripedHtml = stripedHtml.replace(/&#39;/g,'\'');
            stripedHtml = stripedHtml.replace(/&mdash;/g,'—');

/* print the text in sibling block
    you can change or delete the header text of the block "Text from tweet:\n" if you prefer */
            roam42.common.createSiblingBlock(roam42.common.currentActiveBlockUID(), "Text from tweet:\n" + stripedHtml);
        }
});
await roam42.common.sleep(150);
``` %> <%NOBLOCKOUTPUT%>
zidingz commented 3 years ago

Nice, thanks!

JimmyLv commented 3 years ago

It seems not to work anymore.

fbgallet commented 3 years ago

It seems not to work anymore.

Still working for me. Are your other SmartBlocks working ? Is there some error message in the console ?

JimmyLv commented 3 years ago

Thank you. I got to this one and it works 😁 https://roamjs.com/docs/extensions/twitter