Advertisement
Guest User

re-intrafeed2

a guest
Nov 24th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Created by ASUS-PC on 11/8/2016.
  3.  */
  4. var FeedParser = require('feedparser'),
  5.     request = require('request'),
  6.     http = require('http'),
  7.     https = require('https'),
  8.     striptags = require('striptags'),
  9.     size = require('request-image-size'),
  10.     Slack = require('slack-node'),
  11.     mysql = require('mysql'),
  12.     crypto = require('crypto'),
  13.     Emitter = require('tiny-emitter'),
  14.     errors = []
  15.     ;
  16.  
  17. var emitter = new Emitter();
  18.  
  19. //this is for slack
  20. //webhookUri = "https://hooks.slack.com/services/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";
  21. webhookUri = "";
  22.  
  23. slack = new Slack();
  24. slack.setWebhook(webhookUri);
  25. // end slack
  26.  
  27. // setting mysql config
  28. var connection = mysql.createConnection({
  29.     host: "localhost",
  30.     user: "root",
  31.     password: '',
  32.     //user: "intrafeed",
  33.     //password: 'Palmerah$$$i9i7',
  34.     database: "intrafeed",
  35.     charset: 'utf8mb4'
  36.     //waitForConnections : true
  37.     // multipleStatements: true
  38. });
  39.  
  40. connection.connect(function (err) {
  41.     if (err) {
  42.         console.log('Error connecting to Db');
  43.         return;
  44.     }
  45.     console.log('Connection established');
  46. });
  47.  
  48. var intrafeedLinks = "https://intrafeed.co:9000/apit/rssChannels";
  49.  
  50. /*
  51.  End settings and params
  52.  */
  53.  
  54. //fetch('http://rss.detik.com/index.php/detikcom_nasional', 63, '416a5423119a4ec081ca4dd4d948f27f');
  55.  
  56. start();
  57. //5 minutes
  58. setInterval(function () {
  59.     start();
  60. }, 5 * 60 * 1000);
  61.  
  62.  
  63. function start() {
  64.     var channels = null;
  65.  
  66.     request({url: intrafeedLinks, json: true}, function (error, response, body) {
  67.         if (!error && response.statusCode == 200) {
  68.             console.log(body); // Show the HTML for the Google homepage.
  69.             channels = body.channels;
  70.             for (i = 0; i < channels.length; i++) {
  71.  
  72.                 //fetch link
  73.                 //fetch(channels[i].link, channels[i].channelid, channels[i].token);
  74.                 emitter.emit('fetch', channels[i].link, channels[i].channelid, channels[i].token);
  75.             }
  76.         }
  77.     });
  78. }
  79.  
  80. emitter.on("fetch", function (link, channelId, channelToken) {
  81.     fetch(link, channelId, channelToken);
  82. });
  83.  
  84. function fetch(link, channelId, channelToken) {
  85.     var req = request(link);
  86.     //var feedparser = new FeedParser();
  87.     var feedparser = new FeedParser({addmeta: false, resume_saxerror: false});
  88.  
  89.     req.on('error', function (error) {
  90.         // handle any request errors
  91.     });
  92.  
  93.     var itemArray = [];
  94.     var countItemArray = 0;
  95.  
  96.     req.on('response', function (res) {
  97.         var stream = this;
  98.  
  99.         if (res.statusCode != 200) {
  100.             var txt = "Error Request status Code  " + res.statusCode + " link : " + link + " channelid :" + channelId + " error result: " + err;
  101.             if (isNaN(errors[channelId])) {
  102.                 errors[channelId] = 1;
  103.             } else {
  104.                 errors[channelId]++;
  105.             }
  106.             if (errors[channelId] >= 10) {
  107.                 slack.webhook({
  108.                     text: txt
  109.                 }, function (errs, response) {
  110.                     // console.log(response);
  111.                 });
  112.                 errors[channelId] = 0;
  113.             }
  114.             console.log("errors counter : " + channelId + "  " + errors[channelId]);
  115.  
  116.             return this.emit('error', new Error('Bad status code'));
  117.         }
  118.  
  119.         stream.pipe(feedparser);
  120.     });
  121.  
  122.     feedparser.on('error', function (err) {
  123.         var txt = "Error in feed parser module " + link + " channelid :" + channelId + " error result: " + err;
  124.         console.log(txt);
  125.         if (isNaN(errors[channelId])) {
  126.             errors[channelId] = 1;
  127.         } else {
  128.             errors[channelId]++;
  129.         }
  130.  
  131.         if (errors[channelId] >= 10) {
  132.             slack.webhook({
  133.                 text: txt
  134.             }, function (errs, response) {
  135.                 // console.log(response);
  136.             });
  137.             errors[channelId] = 0;
  138.         }
  139.         console.log("errors counter : " + channelId + "  " + errors[channelId]);
  140.     });
  141.  
  142.     feedparser.on('readable', function () {
  143.         // This is where the action is!
  144.         var stream = this
  145.             , meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance
  146.             , item;
  147.  
  148.         while (item = stream.read()) {
  149.             ///store(item, link, channelId, channelToken);
  150.  
  151.             if (item.date == null) {
  152.                 item.date = new Date().toString();
  153.                 // console.log("date is :"+item.date);
  154.                 // return;
  155.             }
  156.  
  157.             if (item.pubDate == null) {
  158.                 item.pubDate = new Date().toString();
  159.                 // console.log("date is :"+item.date);
  160.                 //return;
  161.             }
  162.  
  163.             item.date = new Date(item.date).getTime();
  164.  
  165.             //console.log("date is :"+item.date);
  166.  
  167.             itemArray.push(item);
  168.             //console.log(" -------++----------"+ item +"==============");
  169.             //emitter.emit('store', item, link, channelId, channelToken);
  170.             countItemArray++;
  171.         }
  172.     });
  173. // promise
  174. // end promise
  175.  
  176.     feedparser.on("end", function () {
  177.         console.log(" ++++++++" + link + " total : " + countItemArray + "+++++++++");
  178.  
  179.         var byDate = itemArray.slice(0);
  180.         var sequence = Promise.resolve();
  181.         byDate.sort(function (a, b) {
  182.             var x = a.date;
  183.             var y = b.date;
  184.             return x < y ? -1 : x > y ? 1 : 0;
  185.         });
  186.  
  187.         //buat fungsi baru fechingAll
  188.         fetchingAll(byDate , link, channelId, channelToken);
  189.  
  190.     });
  191. }
  192.  
  193. function fetchingAll(item, link, channelId, channelToken){
  194.     var fetchpromises = host.map(store)
  195.     var sequence = Promise.resolve()
  196.    
  197.     fetchpromises.forEach(function(index,value){
  198.         sequence = sequence.then(function(){
  199.             return index
  200.         }).then(function(url){
  201.             // success method
  202.             //console.log(value + '.' + url + ' success to load!')
  203.             mysqlSave(value.link, value.channelId, value.channelToken, value.data)
  204.            
  205.         }).catch(function(err){
  206.           console.log(err + ' failed to load!')
  207.         })
  208.     })
  209. }
  210.  
  211. emitter.on('store', function (item, link, channelId, channelToken) {
  212.     store(item, link, channelId, channelToken);
  213. });
  214.  
  215. function store(item, link, channelId, channelToken) {
  216.  
  217.     var linkOri = link;
  218.     var linkItem = item.link;
  219.     var title = item.title;
  220.     var description = item.description;
  221.     var pubDate = item.date;
  222.     /* var newDate = new Date(pubDate);
  223.      var tz = newDate.toString().match(/([-\+][0-9]+)\s/)[1];
  224.      var t = newDate.toJSON();
  225.      t = t.substring(0, 19) + tz;
  226.      t = t.replace("+", "-");*/
  227.  
  228.     //console.log("pubDate is :" + pubDate + "link at" + link);
  229.     /* if (pubDate == null) {
  230.      pubDate = new Date().toString();
  231.      }*/
  232.     var createdDate = new Date(pubDate).toISOString().slice(0, 19).replace('T', ' ');
  233.     //console.log(createdDate);
  234.     var author = item.author || "";
  235.     var imagewidth = 0;
  236.     var imageheight = 0;
  237.  
  238.     var isItemImage = item.image;
  239.  
  240.     var itemImage = "";
  241.     var imagelink = "a";
  242.  
  243.     var linkhash = crypto.createHash('sha256').update(linkItem).digest('sha256').toString('hex');
  244.  
  245.     if (isItemImage.hasOwnProperty("url") && isItemImage.url != null) {
  246.         itemImage = isItemImage.url;
  247.     }
  248.     if (itemImage.length > 0) {
  249.         imagelink = itemImage;
  250.     }
  251.  
  252.     if (imagelink.length < 5) {
  253.         imagelink = getImage(description);
  254.     }
  255.  
  256.     if (imagelink.length < 5) {
  257.         if (item.hasOwnProperty("link") && item.link != null) {
  258.             imagelink = item.link;
  259.         }
  260.     }
  261.  
  262.  
  263.     //get from enclosures
  264.     if (imagelink.length < 5) {
  265.         if (item.hasOwnProperty("enclosures") && item.enclosures != null) {
  266.             var itemEnclosures = item.enclosures;
  267.             if (itemEnclosures.length > 0) {
  268.                 if (itemEnclosures[0].hasOwnProperty("url")) {
  269.                     imagelink = itemEnclosures[0].url;
  270.                 }
  271.             }
  272.         }
  273.     }
  274.  
  275.     //get from tag rss:image
  276.     if (imagelink.length < 5) {
  277.         if (item.hasOwnProperty("rss:image") && item["rss:image"] != null) {
  278.             var imageRss = item["rss:image"];
  279.             if (imageRss.hasOwnProperty("url")) {
  280.                 var imageRssUrl = imageRss["url"];
  281.                 if (imageRssUrl.hasOwnProperty("#")) {
  282.                     var imageRssUrlCrash = imageRssUrl["#"];
  283.                     if (imageRssUrlCrash.length > 1) {
  284.                         imagelink = imageRss
  285.                     } else {
  286.                         var meta = item.meta;
  287.                         if (meta.hasOwnProperty("image") && meta.image != null) {
  288.                             var metaImage = meta.image;
  289.                             if (metaImage.hasOwnProperty("url")) {
  290.                                 imagelink = meta["image"]["url"];
  291.                             }
  292.                         }
  293.                     }
  294.                 }
  295.             }
  296.  
  297.         }
  298.     }
  299.  
  300.     //item meta image url
  301.     if (imagelink.length < 5) {
  302.         var meta = item.meta;
  303.         if (meta != null) {
  304.             if (meta.hasOwnProperty("image")) {
  305.                 var metaImage = meta.image;
  306.                 if (metaImage.hasOwnProperty("url")) {
  307.                     imagelink = meta["image"]["url"];
  308.                 }
  309.             }
  310.         }
  311.     }
  312.  
  313.     //get from tag media:content
  314.     if (imagelink < 5) {
  315.         if (item.hasOwnProperty("media:content") && item["media:content"] != null) {
  316.             var mediaContent = item["media:content"];
  317.             imagelink = mediaContent.getAttribute("url");
  318.         }
  319.     }
  320.  
  321.     if (imagelink < 5) {
  322.         if (item.hasOwnProperty("content:encoded")) {
  323.             var contentEncoded = item["content:encoded"];
  324.             if (contentEncoded.hasOwnProperty("#")) {
  325.                 var contentCrash = contentEncoded["#"];
  326.                 imagelink = getImage(contentCrash);
  327.             }
  328.         }
  329.     }
  330.  
  331.     var data = {
  332.         title: title,
  333.         description: striptags(description),
  334.         link: linkItem,
  335.         imagelink: imagelink,
  336.         imagewidth: imagewidth || 0,
  337.         imageheight: imageheight || 0,
  338.         createdDate: createdDate,
  339.         channelid: channelId,
  340.         username: author,
  341.         linkhash: linkhash,
  342.         active: 1
  343.     };
  344.  
  345.     if (imagelink.length > 5) {
  346.         imagelink = imagelink.replace("<![CDATA[", "").replace("]]>", "");
  347.         imagelink = imagelink.replace("'", "").replace('"', "");
  348.         imagelink = imagelink.replace("'", "");
  349.         imagelink = imagelink.replace('"', "");
  350.         imagelink = imagelink.replace("&quot;", "");
  351.         imagelink = striptags(imagelink);
  352.  
  353.         if (imagelink.match(/.js/)) {
  354.             //emitter.emit('mysql-save', link, channelId, channelToken, data);
  355.             //mysqlSave(link, channelId, channelToken, data);
  356.         } else {
  357.             size(imagelink, function (err, dimensions, length) {
  358.                 if (err) {
  359.                     slack.webhook({
  360.                         text: err
  361.                     }, function (errs, response) {
  362.                         // console.log(response);
  363.                     });
  364.                     return true;
  365.                 }
  366.                 if (!err) {
  367.                     if (dimensions != undefined) {
  368.                         imagewidth = dimensions.width;
  369.                         imageheight = dimensions.height;
  370.                     }
  371.  
  372.                     data = {
  373.                         title: title,
  374.                         description: striptags(description),
  375.                         link: linkItem,
  376.                         imagelink: imagelink,
  377.                         imagewidth: imagewidth || 0,
  378.                         imageheight: imageheight || 0,
  379.                         createdDate: createdDate,
  380.                         channelid: channelId,
  381.                         username: author,
  382.                         linkhash: linkhash,
  383.                         active: 1
  384.                     };
  385.  
  386.                     //emitter.emit('mysql-save', link, channelId, channelToken, data);
  387.                     //mysqlSave(link, channelId, channelToken, data);
  388.                 }
  389.  
  390.  
  391.             });
  392.         }
  393.  
  394.  
  395.     } else {
  396.         //emitter.emit('mysql-save', link, channelId, channelToken, data);
  397.         //mysqlSave(link, channelId, channelToken, data);
  398.  
  399.     }
  400.  
  401.  
  402. var fetch = {link:link,channelId:channelId,channelToken:channelToken,data:data};
  403.     return fetch;
  404. }
  405.  
  406.  
  407. emitter.on('mysql-save', function (link, channelId, channelToken, data) {
  408.     // var sql2 = '⁠⁠⁠insert into feed(title,description,link,imagelink,imagewidth,imageheight,channelid,active,linkhash,username) SELECT * FROM (SELECT ? as f1, ?  as f2, ? as f3, ? as f4, 125 as f5,125 as f6,84 as f7,1 as f8, ? as f9, ? as f10) AS tmp WHERE NOT EXISTS (SELECT id FROM feed WHERE channelid= ? and linkhash= ?) LIMIT 1;';
  409.     mysqlSave(link, channelId, channelToken, data);
  410. });
  411.  
  412. function mysqlSave(link, channelId, channelToken, data) {
  413.     var sql = ' INSERT INTO feed(title,description,link,imagelink,imagewidth,imageheight,channelid,active,linkhash,username,createdDate) SELECT * FROM (SELECT ? AS f1,?  AS f2, ? AS f3,? AS f4,? AS f5,? AS f6,? AS f7,? AS f8, ? AS f9, ? as f10, ? as f11) AS tmp WHERE NOT EXISTS (SELECT id FROM feed WHERE channelid= ? AND linkhash= ?) LIMIT 1';
  414.  
  415.     var arrayValue = [data.title, data.description, data.link, data.imagelink, data.imagewidth, data.imageheight, channelId, 1, data.linkhash, data.username, data.createdDate, channelId, data.linkhash];
  416.     var query = connection.query(sql, arrayValue, function (errs, resulr) {
  417.         var txt = data.title + " " + data.link + " " + data.description;
  418.         if (errs) {
  419.             //console.log(errs.toString());
  420.             //console.log(arrayValue.toString());
  421.             //console.log(query);
  422.  
  423.             slack.webhook({
  424.                 text: txt + errs.toString()
  425.             }, function (errs, response) {
  426.                 // console.log(response);
  427.             });
  428.         }
  429.     });
  430. }
  431.  
  432.  
  433. function getImage(string) {
  434.     if (string != null) {
  435.         string = string.replace("<![CDATA[", "").replace("]]>", "");
  436.         string = string.replace("CDATA", "");
  437.         string = string.replace("<figure>", "");
  438.         string = string.replace("</figure>", "");
  439.         string = string.replace("\n", "");
  440.         string = string.replace("\t", "");
  441.  
  442.         var re = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
  443.         var rex = /\ssrc=(?:(?:'([^']*)')|(?:"([^"]*)")|([^\s]*))/i; // match src='a' OR src="a" OR src=a
  444.         var results = null;
  445.         var img = "";
  446.  
  447.         results = re.exec(string);
  448.         if (results) {
  449.             img = results[1];
  450.             if (img.match(/.js/)) {
  451.                 var res = string.match(rex);
  452.                 if (res != null) {
  453.                     img = res[1] || res[2] || res[3]; // get the one that matched
  454.                 }
  455.             }
  456.  
  457.         } else {
  458.             var res = string.match(rex);
  459.             if (res != null) {
  460.                 img = res[1] || res[2] || res[3]; // get the one that matched
  461.             }
  462.         }
  463.  
  464.         return img;
  465.     } else {
  466.         return "";
  467.     }
  468.  
  469. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement