Advertisement
diagnoze

app7

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