Advertisement
Guest User

revisi-intrafeed

a guest
Nov 23rd, 2016
156
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.  
  188. // byDate is array
  189. // maksud gw ma babeh disini coding untuk array byDate
  190. // nanti lo tinggal panggil pake emitter emitter.emit('store', byDate[i], link, channelId, channelToken);
  191.  
  192.        // for (var i in byDate) {
  193.          //   sequence = sequence.then(function(){
  194.           //      return byDate
  195.            // }).then(function(link){
  196.                 // success method
  197.              //   console.log(i + "link at " + link + " : " + new Date(byDate[i].date).toUTCString());
  198.              //   emitter.emit('store', byDate[i], link, channelId, channelToken);
  199.            // }).catch(function(err){
  200.             //    console.log(i + ' failed to load!')
  201.           //  })
  202.           / // console.log(i + "link at " + link + " : " + new Date(byDate[i].date).toUTCString());
  203.             //emitter.emit('store', byDate[i], link, channelId, channelToken);
  204.       //  }
  205.  
  206.     });
  207. }
  208.  
  209. emitter.on('store', function (item, link, channelId, channelToken) {
  210.     store(item, link, channelId, channelToken);
  211. });
  212.  
  213. function store(item, link, channelId, channelToken) {
  214.  
  215.     var linkOri = link;
  216.     var linkItem = item.link;
  217.     var title = item.title;
  218.     var description = item.description;
  219.     var pubDate = item.date;
  220.     /* var newDate = new Date(pubDate);
  221.      var tz = newDate.toString().match(/([-\+][0-9]+)\s/)[1];
  222.      var t = newDate.toJSON();
  223.      t = t.substring(0, 19) + tz;
  224.      t = t.replace("+", "-");*/
  225.  
  226.     //console.log("pubDate is :" + pubDate + "link at" + link);
  227.     /* if (pubDate == null) {
  228.      pubDate = new Date().toString();
  229.      }*/
  230.     var createdDate = new Date(pubDate).toISOString().slice(0, 19).replace('T', ' ');
  231.     //console.log(createdDate);
  232.     var author = item.author || "";
  233.     var imagewidth = 0;
  234.     var imageheight = 0;
  235.  
  236.     var isItemImage = item.image;
  237.  
  238.     var itemImage = "";
  239.     var imagelink = "a";
  240.  
  241.     var linkhash = crypto.createHash('sha256').update(linkItem).digest('sha256').toString('hex');
  242.  
  243.     if (isItemImage.hasOwnProperty("url") && isItemImage.url != null) {
  244.         itemImage = isItemImage.url;
  245.     }
  246.     if (itemImage.length > 0) {
  247.         imagelink = itemImage;
  248.     }
  249.  
  250.     if (imagelink.length < 5) {
  251.         imagelink = getImage(description);
  252.     }
  253.  
  254.     if (imagelink.length < 5) {
  255.         if (item.hasOwnProperty("link") && item.link != null) {
  256.             imagelink = item.link;
  257.         }
  258.     }
  259.  
  260.  
  261.     //get from enclosures
  262.     if (imagelink.length < 5) {
  263.         if (item.hasOwnProperty("enclosures") && item.enclosures != null) {
  264.             var itemEnclosures = item.enclosures;
  265.             if (itemEnclosures.length > 0) {
  266.                 if (itemEnclosures[0].hasOwnProperty("url")) {
  267.                     imagelink = itemEnclosures[0].url;
  268.                 }
  269.             }
  270.         }
  271.     }
  272.  
  273.     //get from tag rss:image
  274.     if (imagelink.length < 5) {
  275.         if (item.hasOwnProperty("rss:image") && item["rss:image"] != null) {
  276.             var imageRss = item["rss:image"];
  277.             if (imageRss.hasOwnProperty("url")) {
  278.                 var imageRssUrl = imageRss["url"];
  279.                 if (imageRssUrl.hasOwnProperty("#")) {
  280.                     var imageRssUrlCrash = imageRssUrl["#"];
  281.                     if (imageRssUrlCrash.length > 1) {
  282.                         imagelink = imageRss
  283.                     } else {
  284.                         var meta = item.meta;
  285.                         if (meta.hasOwnProperty("image") && meta.image != null) {
  286.                             var metaImage = meta.image;
  287.                             if (metaImage.hasOwnProperty("url")) {
  288.                                 imagelink = meta["image"]["url"];
  289.                             }
  290.                         }
  291.                     }
  292.                 }
  293.             }
  294.  
  295.         }
  296.     }
  297.  
  298.     //item meta image url
  299.     if (imagelink.length < 5) {
  300.         var meta = item.meta;
  301.         if (meta != null) {
  302.             if (meta.hasOwnProperty("image")) {
  303.                 var metaImage = meta.image;
  304.                 if (metaImage.hasOwnProperty("url")) {
  305.                     imagelink = meta["image"]["url"];
  306.                 }
  307.             }
  308.         }
  309.     }
  310.  
  311.     //get from tag media:content
  312.     if (imagelink < 5) {
  313.         if (item.hasOwnProperty("media:content") && item["media:content"] != null) {
  314.             var mediaContent = item["media:content"];
  315.             imagelink = mediaContent.getAttribute("url");
  316.         }
  317.     }
  318.  
  319.     if (imagelink < 5) {
  320.         if (item.hasOwnProperty("content:encoded")) {
  321.             var contentEncoded = item["content:encoded"];
  322.             if (contentEncoded.hasOwnProperty("#")) {
  323.                 var contentCrash = contentEncoded["#"];
  324.                 imagelink = getImage(contentCrash);
  325.             }
  326.         }
  327.     }
  328.  
  329.     var data = {
  330.         title: title,
  331.         description: striptags(description),
  332.         link: linkItem,
  333.         imagelink: imagelink,
  334.         imagewidth: imagewidth || 0,
  335.         imageheight: imageheight || 0,
  336.         createdDate: createdDate,
  337.         channelid: channelId,
  338.         username: author,
  339.         linkhash: linkhash,
  340.         active: 1
  341.     };
  342.  
  343.     if (imagelink.length > 5) {
  344.         imagelink = imagelink.replace("<![CDATA[", "").replace("]]>", "");
  345.         imagelink = imagelink.replace("'", "").replace('"', "");
  346.         imagelink = imagelink.replace("'", "");
  347.         imagelink = imagelink.replace('"', "");
  348.         imagelink = imagelink.replace("&quot;", "");
  349.         imagelink = striptags(imagelink);
  350.  
  351.         if (imagelink.match(/.js/)) {
  352.             //emitter.emit('mysql-save', link, channelId, channelToken, data);
  353.             mysqlSave(link, channelId, channelToken, data);
  354.         } else {
  355.             size(imagelink, function (err, dimensions, length) {
  356.                 if (err) {
  357.                     slack.webhook({
  358.                         text: err
  359.                     }, function (errs, response) {
  360.                         // console.log(response);
  361.                     });
  362.                     return true;
  363.                 }
  364.                 if (!err) {
  365.                     if (dimensions != undefined) {
  366.                         imagewidth = dimensions.width;
  367.                         imageheight = dimensions.height;
  368.                     }
  369.  
  370.                     data = {
  371.                         title: title,
  372.                         description: striptags(description),
  373.                         link: linkItem,
  374.                         imagelink: imagelink,
  375.                         imagewidth: imagewidth || 0,
  376.                         imageheight: imageheight || 0,
  377.                         createdDate: createdDate,
  378.                         channelid: channelId,
  379.                         username: author,
  380.                         linkhash: linkhash,
  381.                         active: 1
  382.                     };
  383.  
  384.                     //emitter.emit('mysql-save', link, channelId, channelToken, data);
  385.                     mysqlSave(link, channelId, channelToken, data);
  386.                 }
  387.  
  388.  
  389.             });
  390.         }
  391.  
  392.  
  393.     } else {
  394.         //emitter.emit('mysql-save', link, channelId, channelToken, data);
  395.         mysqlSave(link, channelId, channelToken, data);
  396.  
  397.     }
  398.  
  399.  
  400.     return true;
  401. }
  402.  
  403.  
  404. emitter.on('mysql-save', function (link, channelId, channelToken, data) {
  405.     // 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;';
  406.     mysqlSave(link, channelId, channelToken, data);
  407. });
  408.  
  409. function mysqlSave(link, channelId, channelToken, data) {
  410.     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';
  411.  
  412.     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];
  413.     var query = connection.query(sql, arrayValue, function (errs, resulr) {
  414.         var txt = data.title + " " + data.link + " " + data.description;
  415.         if (errs) {
  416.             //console.log(errs.toString());
  417.             //console.log(arrayValue.toString());
  418.             //console.log(query);
  419.  
  420.             slack.webhook({
  421.                 text: txt + errs.toString()
  422.             }, function (errs, response) {
  423.                 // console.log(response);
  424.             });
  425.         }
  426.     });
  427. }
  428.  
  429.  
  430. function getImage(string) {
  431.     if (string != null) {
  432.         string = string.replace("<![CDATA[", "").replace("]]>", "");
  433.         string = string.replace("CDATA", "");
  434.         string = string.replace("<figure>", "");
  435.         string = string.replace("</figure>", "");
  436.         string = string.replace("\n", "");
  437.         string = string.replace("\t", "");
  438.  
  439.         var re = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
  440.         var rex = /\ssrc=(?:(?:'([^']*)')|(?:"([^"]*)")|([^\s]*))/i; // match src='a' OR src="a" OR src=a
  441.         var results = null;
  442.         var img = "";
  443.  
  444.         results = re.exec(string);
  445.         if (results) {
  446.             img = results[1];
  447.             if (img.match(/.js/)) {
  448.                 var res = string.match(rex);
  449.                 if (res != null) {
  450.                     img = res[1] || res[2] || res[3]; // get the one that matched
  451.                 }
  452.             }
  453.  
  454.         } else {
  455.             var res = string.match(rex);
  456.             if (res != null) {
  457.                 img = res[1] || res[2] || res[3]; // get the one that matched
  458.             }
  459.         }
  460.  
  461.         return img;
  462.     } else {
  463.         return "";
  464.     }
  465.  
  466. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement