Advertisement
Guest User

nodejspromise

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