tapestry-attachment-extraction.js
                        
                             · 1011 B · JavaScript
                        
                    
                    
                      
                        Raw
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            /*
  Attachment Extracting
  for Iconfactory's Tapestry plugins
  Grabs urls from a string, like `content_html` in a JSON Feed, and makes them attachments.
  Made to be used in your Tapestry plugins like so:
  ```js
    const myItem = Item.createWithUriDate(url, date);
    myItem.attachments = extractAttachments(content_html, [rest?.external_url, rest?.image])
  ```
*/
const URL_REGEX =
  /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
const MEDIA_EXT = ["png", "tif", "tiff", "jpeg", "jpg", "gif", "bmp", "bmpf", "ico", "cur", "xbm", "aac", "aiff", "aifc", "avi", "ac3", "mp4", "m2v", "ts", "mpg", "mp2", "mp3", "au", "3gp", "3g2"];
function extractAttachments(from = "", exclude = []) {
  return (from.match(URL_REGEX) || [])
    .filter((url) => !exclude.includes(url))
    .map((url) =>
      MEDIA_EXT.some((ext) => url.includes(`.${ext}`))
        ? MediaAttachment.createWithUrl(url)
        : LinkAttachment.createWithUrl(url)
    );
}
                | 1 | /* | 
| 2 | Attachment Extracting | 
| 3 | for Iconfactory's Tapestry plugins | 
| 4 | |
| 5 | Grabs urls from a string, like `content_html` in a JSON Feed, and makes them attachments. | 
| 6 | |
| 7 | Made to be used in your Tapestry plugins like so: | 
| 8 | |
| 9 | ```js | 
| 10 | const myItem = Item.createWithUriDate(url, date); | 
| 11 | myItem.attachments = extractAttachments(content_html, [rest?.external_url, rest?.image]) | 
| 12 | ``` | 
| 13 | */ | 
| 14 | |
| 15 | const URL_REGEX = | 
| 16 | /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g; | 
| 17 | const MEDIA_EXT = ["png", "tif", "tiff", "jpeg", "jpg", "gif", "bmp", "bmpf", "ico", "cur", "xbm", "aac", "aiff", "aifc", "avi", "ac3", "mp4", "m2v", "ts", "mpg", "mp2", "mp3", "au", "3gp", "3g2"]; | 
| 18 | |
| 19 | function extractAttachments(from = "", exclude = []) { | 
| 20 | return (from.match(URL_REGEX) || []) | 
| 21 | .filter((url) => !exclude.includes(url)) | 
| 22 | .map((url) => | 
| 23 | MEDIA_EXT.some((ext) => url.includes(`.${ext}`)) | 
| 24 | ? MediaAttachment.createWithUrl(url) | 
| 25 | : LinkAttachment.createWithUrl(url) | 
| 26 | ); | 
| 27 | } | 
| 28 |