Ejemplo n.º 1
0
Archivo: index.js Proyecto: Eiiki/apis
app.get('/address/:address?', function(req, res) {
    var address = req.query.address || req.params.address || '';

    if(address === '') {
      return res.json(431, {error: 'Please provide a valid address to lookup'});
    }

    address = address.replace(' ', '+');

    request.get({
      headers: {'User-Agent': h.browser()},
      url: 'https://api.postur.is/PosturIs/ws.asmx/GetPostals?address=' + address
    }, function(error, response, body) {
      if(error || response.statusCode !== 200) {
        return res.json(500,{error:'www.postur.is refuses to respond or give back data'});
      }

      // There is a enclosing () in the response
      var data  = JSON.parse(body.replace(/[()]/g, ''));
      data = _.flatten(data);

      var results = _.map(data, function(elem) {
        return {
          street: elem.Gata,
          house: elem.Husnumer,
          zip: elem.Postnumer,
          city: elem.Sveitafelag,
          apartment: elem.Ibud,
          letter: elem.Stafur
        };
      });

      return res.cache().json({ results: results });
    });
});
Ejemplo n.º 2
0
Archivo: 365.js Proyecto: Joddsson/apis
const getFeed = function (url, callback) {
  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error) return callback(new Error(`${url} did not respond`))

    parseFeed(callback, body)
  })
}
Ejemplo n.º 3
0
var getFeed = function(url, callback) {
  request.get({
    headers: {'User-Agent': h.browser()},
    url: url
  }, function (error, response, body) {
    if (error) return callback(new Error(url + ' did not respond'));

    parseFeed(callback, body);
  });
};
Ejemplo n.º 4
0
app.get('/carparks', (req, res) => {
  const url = 'http://www.bilastaedasjodur.is/'

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({
        error: 'www.bilastaedasjodur.is refuses to respond or give back data',
      })
    }

    try {
      // FIXME: What is the point of this? It doesn't seem to be used anywhere
      // eslint-disable-next-line no-unused-vars
      const data = $(body)
    } catch (exc) {
      return res.status(500).json({ error: 'Could not parse body' })
    }

    const obj = { results: [] }
    const hus = $('.hus', $(body))

    const js = body.match(/LatLng\((.*?)\)/g)

    function parseCoordinates(str) {
      try {
        const Regexp = /(?:^|\s)LatLng.(.*?)\)(?:\s|$)/g
        const match = Regexp.exec(str)
        return match[1].split(', ')
      } catch (exc) {
        return null
      }
    }

    for (let i = 0; i < hus.length; i++) {
      const that = hus[i]
      const freeSpaces = parseInt($(that).find('.ib.free h1').text(), 10)
      const totalSpaces = parseInt($(that).find('.ib.total h1').text(), 10)

      obj.results.push({
        name: $(that).find('aside h2').text(),
        address: $(that).find('h5').text(),
        parkingSpaces: {
          free: !isNaN(freeSpaces) ? freeSpaces : null,
          total: !isNaN(totalSpaces) ? totalSpaces : null,
        },
        coordinates: parseCoordinates(js[i]),
      })
    }

    return res.cache(180).json(obj)
  })
})
Ejemplo n.º 5
0
Archivo: index.js Proyecto: Eiiki/apis
app.get('/company', function(req, res, next){
    
    var queryString = {
        nafn: req.query.name || '',
        heimili: req.query.address || '',
        kt: req.query.socialnumber || '',
        vsknr: req.query.vsknr || ''
    };

    request.get({
        headers: {'User-Agent': h.browser()},
        url: 'http://www.rsk.is/fyrirtaekjaskra/leit',
        qs: queryString
    }, function(error, response, body){
        if(error || response.statusCode !== 200) {
            return res.json(500,{error:'www.rsk.is refuses to respond or give back data'});
        }

        var obj = { results: [] },
              $ = cheerio.load(body);

        if($('.resultnote').length === 0){
            var tr = $('.boxbody > .nozebra tbody tr').first();
            if (tr.length > 0) {
                var name = $('.boxbody > h1').html(),
                    sn = $('.boxbody > h1').html();

                obj.results.push({
                    name: name.substring(0,name.indexOf('(')-1),
                    sn: sn.substring(sn.length-11,sn.length-1),
                    active: $('p.highlight').text().length === 0 ? 1 : 0,
                    address: tr.find('td').eq(0).text()
                });
            }
        } else {
            $('table tr').slice(1).each(function() {

                var td = $(this).find('td');
                var nameRoot = td.eq(1).text();
                var felagAfskrad = "(Félag afskráð)";

                obj.results.push({
                    name: nameRoot.replace("\n","").replace(felagAfskrad,"").replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
                    sn: td.eq(0).text(),
                    active: nameRoot.indexOf(felagAfskrad) > -1 ? 0 : 1,
                    address: td.eq(2).text()
                });

            }); 
        }
        
        return res.cache(86400).json(obj);
    });
});
Ejemplo n.º 6
0
Archivo: index.js Proyecto: Loknar/apis
app.get('/isnic', (req, res) => {
  const domainName = req.query.domain || ''

  if (!domainName) {
    return res.status(431).json({ error: 'Please provide a valid domainName to lookup' })
  }

  const url = `https://www.isnic.is/en/whois/search?yt1972183=%C3%81fram&type=all&query=${domainName}`

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({
        error: 'www.isnic.is refuses to respond or give back data',
      })
    }

    const data = $(body)

    const obj = {
      results: [],
    }

    const fields = []

    data.find('.miniWhois .row').each(function () {
      const label = $(this).find('label').text().trim()
      const val = $(this).text().replace(label, '').trim()

      fields.push({ val, label })
    })

    if (fields.length > 0) {
      obj.results.push({
        domain: (fields.find(x => x.label === 'Domain:') || { val: '' }).val,
        registrantname: (fields.find(x => x.label === 'Registrant name:') || { val: '' }).val,
        address: (fields.find(x => x.label === 'Address:') || { val: '' }).val,
        city: (fields.find(x => x.label === 'City/Municipality:') || { val: '' }).val,
        postalCode: (fields.find(x => x.label === 'Postal code:') || { val: '' }).val,
        country: (fields.find(x => x.label === 'Country:') || { val: '' }).val,
        phone: (fields.find(x => x.label === 'Phone:') || { val: '' }).val,
        email: (fields.find(x => x.label === 'E-mail:') || { val: '' }).val,
        registered: (fields.find(x => x.label === 'Registered:') || { val: '' }).val,
        expires: (fields.find(x => x.label === 'Expires:') || { val: '' }).val,
        lastChange: (fields.find(x => x.label === 'Last change:') || { val: '' }).val,
      })
    }

    return res.cache(86400).json(obj)
  })
})
Ejemplo n.º 7
0
Archivo: index.js Proyecto: Eiiki/apis
app.get('/car', function(req, res){
	var carPlate = req.query.number || req.query.carPlate || '';
	
	if(!carPlate)
		return res.json(431,{error:'Please provide a valid carPlate to lookup'});

	// Encode carPlate so that Icelandic characters will work
	carPlate = encodeURIComponent(carPlate);

	var url = 'http://www.samgongustofa.is/umferd/okutaeki/okutaekjaskra/uppfletting?vq=' + carPlate;

	request.get({
		headers: {'User-Agent': h.browser()},
		url: url
	}, function(error, response, body) {
		if(error || response.statusCode !== 200) {
			return res.json(500,{error:'www.samgongustofa.is refuses to respond or give back data'});
		}

		var data = $(body);

		var obj = {
			results: []
		};

		var fields = [];

		data.find('.vehicleinfo ul li').each(function() {
			var val = $(this).find('span').text();

			fields.push(val);
		});

		if (fields.length > 0) {
			obj.results.push({
				type: fields[0],
				subType: fields[0].substring(fields[0].indexOf('-')+2,fields[0].indexOf('(')-1),
				color: fields[0].substring(fields[0].indexOf('(')+1,fields[0].indexOf(')')),
				registryNumber: fields[1],
				number: fields[2],
				factoryNumber: fields[3],
				registeredAt: fields[4],
				pollution: fields[5],
				weight: fields[6],
				status: fields[7],
				nextCheck: fields[8]
			});
		} 
		
		return res.cache().json(obj);
	});
});
Ejemplo n.º 8
0
/** Methods **/

/* Fetches the weather data and returns a JS object in a callback */
function getJsonData(url, callback){
  request.get({
      headers: {'User-Agent': h.browser()},
      url: url
    }, function (error, response, body) {

      if (error) throw new Error(url + ' did not respond');
      
      parseString(body, function (err, result, title) {
        callback(result);
    });
  });
}
Ejemplo n.º 9
0
Archivo: m5.js Proyecto: koddsson/apis
app.get('/currency/m5', (req, res) => {
  // FIXME: Not being used, comment out for now
  // const currencyNames = {
  //   s: ['USD', 'DKK', 'EUR', 'JPY', 'CAD', 'NOK', 'GBP', 'CHF', 'SEK', 'TWI', 'XDR', 'ISK'],
  //   l: [
  //     'Bandarískur dalur',
  //     'Dönsk króna',
  //     'Evra',
  //     'Japanskt jen',
  //     'Kanadískur dalur',
  //     'Norsk króna',
  //     'Sterlingspund',
  //     'Svissneskur franki',
  //     'Sænsk króna',
  //     'Gengisvísitala',
  //     'SDR',
  //     'Íslensk króna',
  //   ],
  // }

  request.get({
    headers: { 'User-Agent': h.browser() },
    url: 'http://www.m5.is/?gluggi=gjaldmidlar',
  }, (err, response, body) => {
    if (err || response.statusCode !== 200) {
      return res.status(500).json({ error: 'www.m5.is refuses to respond or give back data' })
    }

    const $ = cheerio.load(body)
    const currencies = []

    $('.table-striped tr').each(function () {
      const tds = $(this).find('td')
      const name = tds.eq(0).text()

      if (name) {
        currencies.push({
          shortName: name,
          longName: h.currency[name].long,
          value: parseFloat(tds.eq(2).text().replace(',', '.')),
          askValue: 0,
          bidValue: 0,
          changeCur: parseFloat(tds.eq(4).text().replace(',', '.')),
          changePer: parseFloat(tds.eq(5).text().replace(/\((.*)%\)/, '$1').replace(',', '.')),
        })
      }
    })

    return res.cache(60).json({ results: currencies })
  })
})
Ejemplo n.º 10
0
app.get('/carparks', function(req, res){

	var url = 'http://www.bilastaedasjodur.is/';

	request.get({
		headers: {'User-Agent': h.browser()},
		url: url
	}, function(error, response, body){
		if(error || response.statusCode !== 200)
			return res.status(500).json({error:'www.bilastaedasjodur.is refuses to respond or give back data'});

		try{
			var data = $(body);
		}catch(error){
			return res.status(500).json({error:'Could not parse body'});
		}

		var	obj = { results: []};
		var hus = $('.hus', $(body));

		var js = body.match(/LatLng\((.*?)\)/g);

		function parseCoordinates(str) {
			try {
				var Regexp = /(?:^|\s)LatLng.(.*?)\)(?:\s|$)/g;
				var match = Regexp.exec(str);
				return match[1].split(', ');
			}catch(error) {
				return null;
			}
		}

		for(var i=0; i<hus.length; i++) {
			var that = hus[i];
			var freeSpaces = parseInt($(that).find('.ib.free h1').text());
			var totalSpaces = parseInt($(that).find('.ib.total h1').text());

			obj.results.push({
				name: $(that).find('aside h2').text(),
				address: $(that).find('h5').text(),
				parkingSpaces: {
					free: !isNaN(freeSpaces) ? freeSpaces : null,
					total: !isNaN(totalSpaces) ? totalSpaces : null
				},
				coordinates: parseCoordinates(js[i])
			});
		}

		return res.cache(180).json(obj);
	});
});
Ejemplo n.º 11
0
/* Fetches the weather data and returns a JS object in a callback */
function getJsonData(url, callback) {
  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error) {
      throw new Error(`${url} did not respond`)
    }

    parseString(body, (err, result) => {
      callback(result)
    })
  })
}
Ejemplo n.º 12
0
Archivo: index.js Proyecto: Eiiki/apis
app.get('/declension/:word', function(req, res) {
	var word = req.params.word;
	baseUrl.query = {'q': word};

	var params = {
		url: url.format(baseUrl),
		headers: {
			'User-Agent': helper.browser(),
		},
	};

	getDeclensions(function(body) {
		return res.json(parseTable(body));
  	}, params);
});
Ejemplo n.º 13
0
app.get('/declension/:word', (req, res) => {
  const word = req.params.word
  baseUrl.query = { q: word }

  const params = {
    url: url.format(baseUrl),
    headers: {
      'User-Agent': helper.browser(),
    },
  }

  getDeclensions((body) => {
    return res.json(parseTable(body))
  }, params)
})
Ejemplo n.º 14
0
app.get('/sports/football', (req, res) => {
  const url = 'http://www.ksi.is/mot/naestu-leikir/'
  request.get(
    {
      headers: { 'User-Agent': h.browser() },
      url,
    },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ error: 'www.ksi.is refuses to respond or give back data' })
      }

      let $

      try {
        $ = cheerio.load(body)
      } catch (exc) {
        return res.status(500).json({ error: 'Could not parse body' })
      }

      const obj = { results: [] }
      const fields = ['counter', 'date', 'time', 'tournament', 'location', 'homeTeam', 'awayTeam']
      try {
        $('#leikir-tafla tr').each((key, element) => {
          if (key !== 0) {
            const game = {}
            $('td', element).each(function (key2) {
              const val = $(this).text()
              if (val && val.trim() && val !== '' && val !== 0 && val !== '\t' && val !== '\n') {
                game[fields[key2]] = val
              }
            })

            // Checking whether it has the necessary fields
            if (game.counter && game.date && game.time && game.tournament && game.location
              && game.homeTeam && game.awayTeam) {
              obj.results.push(game)
            }
          }
        })
      } catch (exc) {
        return res.status(500).json({ error: 'Could not parse the game data' })
      }

      return res.json(obj)
    }
  )
})
Ejemplo n.º 15
0
app.get('/tv/stod2', function (req, res) {
    var url = 'http://stod2.is/XML--dagskrar-feed/XML-Stod-2-dagurinn';

    request.get({
        headers: {'User-Agent': h.browser()},
        url: url
    }, function (error, response, body) {
        if (error) throw new Error(url + ' did not respond');

        parseStod2(function (data) {
            res.cache(1800).json(200, {
                results: data
            })
        }, body);
    })
});
Ejemplo n.º 16
0
app.get('/sports/handball', (req, res) => {
  const url = 'http://hsi.is/library/motamal/naestu.htm'
  request.get(
    {
      headers: { 'User-Agent': h.browser() },
      url,
    },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ error: 'www.hsi.is refuses to respond or give back data' })
      }

      let $
      try {
        $ = cheerio.load(body)
      } catch (exc) {
        return res.status(500).json({ error: 'Could not parse body' })
      }

      const obj = { results: [] }
      const fields = ['Date', 'Time', 'Tournament', 'Venue', 'Teams']

      try {
        $('table').eq(1).find('tr').each(function (key) {
          if (key !== 0) {
            const game = {}
            $('td', this).each(function (key2) {
              const val = $(this).text().trim()
              if (val && val !== '' && val !== 0) {
                game[fields[key2]] = val
              }
            })

            if (game.Date && game.Time && game.Tournament && game.Venue && game.Teams) {
              obj.results.push(game)
            }
          }
        })
      } catch (exc) {
        return res.status(500).json({ error: `Could not parse the game data: ${error}` })
      }

      return res.json(obj)
    }
  )
})
Ejemplo n.º 17
0
function footballLeagues(url, req, res) {
  request.get(
    {
      headers: { 'User-Agent': h.browser() },
      url,
    },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ error: 'www.ksi.is refuses to respond or give back data' })
      }

      let $

      try {
        $ = cheerio.load(body)
      } catch (exc) {
        return res.status(500).json({ error: 'Could not parse body' })
      }

      const obj = { results: [] }
      const fields = ['counter', 'date', 'time', 'teams', 'location', 'scores']
      try {
        $('#leikir-tafla tr').each(function (key) {
          if (key !== 0) {
            const game = {}
            $('td', this).each(function (key2) {
              const val = $(this).text()
              if (val !== 0 && val !== '\t' && val !== '\n' && fields[key2]) {
                game[fields[key2]] = val
              }
            })

            // Checking whether it has the necessary fields
            if (game.counter && game.date && game.time && game.teams && game.location) {
              obj.results.push(game)
            }
          }
        })
      } catch (exc) {
        return res.status(500).json({ error: 'Could not parse the game data' })
      }

      return res.json(obj)
    }
  )
}
Ejemplo n.º 18
0
function queryData(callback) {
  const url = 'https://raw.githubusercontent.com/gasvaktin/gasvaktin/master/vaktin/gas.min.json'
  const headers = {
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.8,is;q=0.6',
    'Cache-Control': 'max-age=0',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': h.browser(),
  }
  request.get({
    headers,
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      callback(error, response, '')
    }
    callback(error, response, body)
  })
}
Ejemplo n.º 19
0
/* Handles the request for a specific request URL */
function handleRequest(providedUrl, req, res) {
  let $
  // Check for the filter parameter
  const filter = req.params.filter || req.query.filter || req.query.search || ''

  // Add name filtering if it is requested
  let url = providedUrl || ''
  if (filter !== '') {
    url += `&Nafn=${filter}`
  }

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({ error: 'www.island.is refuses to respond or give back data' })
    }

    try {
      $ = cheerio.load(body)
    } catch (exc) {
      return res.status(500).json({ error: 'Could not parse body' })
    }

    const obj = { results: [] }

    // Clear data regarding the acceptance date of the name (not needed)
    $('.dir li i').each(() => {
      $(this).remove()
    })

    // Loop through all the names in the list and add them to our array
    $('.dir li').each(() => {
      const name = $(this).text()
      obj.results.push(name.trim())
    })

    // Return the results as JSON and cache for 24 hours
    return res.cache(86400).json(obj)
  })
}
Ejemplo n.º 20
0
app.get('/tv/:var(skjar1|skjareinn)', function (req, res) {
  res.status(503).json({error: 'Source page has changed. Scraping needs to be re-implemented'});

  var url = 'http://www.skjarinn.is/einn/dagskrarupplysingar/?channel_id=7&output_format=xml';

  request.get({
    headers: {'User-Agent': h.browser()},
    url: url
  }, function (error, response, body) {
    if(error || response.statusCode !== 200){
      return res.status(504).json({error:'skjarinn.is is not responding with the right data'});
    }

    parseSkjar1(function (data) {
      res.cache(1800).json(200, {
        results: data
      });
    }, body);
  });
});
Ejemplo n.º 21
0
const lookupCar = plate => new Promise((resolve, reject) => {
  // Encode carPlate so that Icelandic characters will work
  const carPlate = encodeURIComponent(plate)
  const url = `http://www.samgongustofa.is/umferd/okutaeki/okutaekjaskra/uppfletting?vq=${carPlate}`

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      reject('www.samgongustofa.is refuses to respond or give back data')
    }

    const data = $(body)
    const fields = []

    data.find('.vehicleinfo ul li').each(function () {
      const val = $(this).find('span').text()
      fields.push(val)
    })

    if (fields.length > 0) {
      resolve({
        type: fields[0],
        subType: fields[0].substring(fields[0].indexOf('-') + 2, fields[0].indexOf('(') - 1),
        color: fields[0].substring(fields[0].indexOf('(') + 1, fields[0].indexOf(')')),
        registryNumber: fields[1],
        number: fields[2],
        factoryNumber: fields[3],
        registeredAt: fields[4],
        pollution: fields[5],
        weight: fields[6],
        status: fields[7],
        nextCheck: fields[8],
      })
    } else {
      reject(`No car found with the registry number ${plate}`)
    }
  })
})
Ejemplo n.º 22
0
function queryTimestamps(callback) {
  const url = 'https://gist.github.com/gasvaktin'
  const headers = {
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.8,is;q=0.6',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
    Host: 'gist.github.com',
    Pragma: 'no-cache',
    'Upgrade-Insecure-Requests': 1,
    'User-Agent': h.browser(),
  }
  request.get({
    headers,
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      callback(error, response, '')
    }
    callback(error, response, body)
  })
}
Ejemplo n.º 23
0
/* Handles the request for a specific request URL */
function handleRequest(url, req, res) {
	// Check for the filter parameter
	var filter = req.params.filter || req.query.filter || req.query.search || '';

	// Add name filtering if it is requested
	if (filter !== ''){
		url += '&Nafn=' + filter;
	}

	request.get({
		headers: {'User-Agent': h.browser()},
		url: url
	}, function(error, response, body){
		if(error || response.statusCode !== 200)
			return res.status(500).json({error:'www.island.is refuses to respond or give back data'});

		try{
			var $ = cheerio.load(body);
		}catch(error){
			return res.status(500).json({error:'Could not parse body'});
		}

		var	obj = { results: []};

		// Clear data regarding the acceptance date of the name (not needed)
		$('.dir li i').each(function(key) {
			$(this).remove();
		});

		// Loop through all the names in the list and add them to our array
		$('.dir li').each(function(key){
			var name = $(this).text();
			obj.results.push(name.trim());
		});

		// Return the results as JSON and cache for 24 hours
		return res.cache(86400).json(obj);
	});
}
Ejemplo n.º 24
0
const lookupAddresses = address => new Promise((resolve, reject) => {
  request.get({
    headers: { 'User-Agent': h.browser() },
    url: `https://api.postur.is/PosturIs/ws.asmx/GetPostals?address=${address}`,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      reject(error)
    }

    // There is a enclosing () in the response
    const data = _.flatten(JSON.parse(body.replace(/[()]/g, '')))

    const results = _.map(data, elem => ({
      street: elem.Gata,
      house: elem.Husnumer,
      zip: elem.Postnumer,
      city: elem.Sveitafelag,
      apartment: elem.Ibud,
      letter: elem.Stafur,
    }))
    resolve(results)
  })
})
Ejemplo n.º 25
0
app.get('/golf/clubs', (req, res) => {
  request.get({
    // http://stackoverflow.com/a/20091919
    rejectUnauthorized: false,
    headers: { 'User-Agent': h.browser() },
    url: 'http://mitt.golf.is/pages/rastimar/',
  }, (err, response, html) => {
    if (err || response.statusCode !== 200) {
      return res.status(500).json({
        error: 'mitt.golf.is refuses to respond or give back data',
      })
    }

    const $ = cheerio.load(html)
    // Skip the first element.
    const rows = $('table.golfTable tr').slice(2)
    return res.cache(3600).json({
      results: _.map(rows, (row) => {
        const $row = $(row)
        const url = (
          $row.children('td.club').children('a').attr('href')
        )

        const query = parseUrl(url, true).query

        return {
          abbreviation: $row.children('td.abbreviation').html(),
          club: {
            id: query.club,
            name: $row.children('td.club').children('a').html(),
          },
          location: $row.children('td.location').html(),
        }
      }),
    })
  })
})
Ejemplo n.º 26
0
function queryData(id, name, origin, microchip, callback) {
  const url = 'http://www.worldfengur.com/freezone_horse.jsp?c=EN'
  const headers = {
    'User-Agent': h.browser(),
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Content-Type': 'application/x-www-form-urlencoded',
  }

  // Encoding parameters so Icelandic characters will work
  // Hacking around to get ISO 8859-1 encoded string, pls unhack if you know better way
  const encodedName = encodeURIComponent(escape(name)).replace(/%25/g, '%')
  const encodedOrigin = encodeURIComponent(escape(origin)).replace(/%25/g, '%')

  /* eslint-disable prefer-template */
  const formData = (
    'fnr=' + id +
    '&nafn=' + encodedName +
    '&uppruni=' + encodedOrigin +
    '&ormerki=' + microchip +
    '&leitahnappur=Search+&leita=1'
  )
  /* eslint-enable */

  request.post({
    headers,
    url,
    body: formData,
    encoding: null,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      callback(error, response, '')
    }
    const htmlPage = iconv.decode(body, 'iso-8859-1')
    callback(error, response, htmlPage)
  })
}
Ejemplo n.º 27
0
app.get('/tv/ruv', function (req, res) {
    var url = 'http://muninn.ruv.is/files/xml/ruv/';

    if (req.params.date) {
        if (moment(req.params.date).isValid()) {
            var date = moment(req.params.date);
            // Example : http://muninn.ruv.is/files/xml/ruv/2013-06-11/
            url += date.format('YYYY-MM-DD');
        }
    }

    request.get({
        headers: {'User-Agent': h.browser()},
        url: url
    }, function (error, response, body) {
        if (error) throw new Error(url + ' did not respond');

        parseRuv(function (data) {
            res.cache(1800).json(200, {
                results: data
            })
        }, body);
    });
});
Ejemplo n.º 28
0
app.get('/golf/teetimes', (req, res) => {
  const clubId = req.query.club
  if (!clubId) {
    return res.status(500).json({
      error: 'Please provide a valid club id to lookup',
    })
  }

  request.get({
    // http://stackoverflow.com/a/20091919
    rejectUnauthorized: false,
    headers: { 'User-Agent': h.browser() },
    url: `http://mitt.golf.is/pages/rastimar/rastimayfirlit/?club=${clubId}`,
  }, (err, response, html) => {
    if (err || response.statusCode !== 200) {
      return res.status(500).json({
        error: 'mitt.golf.is refuses to respond or give back data',
      })
    }
    const $ = cheerio.load(html)
    const rows = $('table.teeTimeTable tbody').children()
    let time = ''
    return res.cache().json({
      results: _.map(rows, (row) => {
        const $row = $(row)
        time = $row.children('td.time').html() === null ? time : $row.children('td.time').html()
        return {
          time,
          name: $($row.children('td.name')).html(),
          club: $($row.children('td.club')).html(),
          handicap: $($row.children('td.handicap')).html(),
        }
      }),
    })
  })
})
Ejemplo n.º 29
0
app.get('/flight', function(req, res){
    var data = req.query;
    var url = '';

    if(!data.type) data.type = '';
    if(!data.language) data.language = '';

    if(data.type == 'departures' && data.language == 'is'){
        url = 'http://www.kefairport.is/Flugaaetlun/Brottfarir/';
    }else if(data.type == 'departures' && data.language == 'en'){
        url = 'http://www.kefairport.is/English/Timetables/Departures/';
    }else if(data.type == 'arrivals' && data.language == 'is'){
        url = 'http://www.kefairport.is/Flugaaetlun/Komur/';
    }else if(data.type == 'arrivals' && data.language == 'en'){
        url = 'http://www.kefairport.is/English/Timetables/Arrivals/';
    }else{
        url = 'http://www.kefairport.is/English/Timetables/Arrivals/';
    }

    request.get({
        headers: {'User-Agent': h.browser()},
        url: url
    }, function(error, response, body){
        if(error || response.statusCode !== 200)
            return res.status(500).json({error:'www.kefairport.is refuses to respond or give back data'});

        try {
          var $ = cheerio.load(body);
        } catch(err) {
            return res.status(500).json({error:'Could not parse body'});
        }

        var obj = { results: []};

        $('table tr').each(function(key){
            if(key !== 0){
                var flight = {};
                if(data.type === 'departures') {
                    flight = {
                        'date': $(this).children('td').slice(0).html(),
                        'flightNumber': $(this).children('td').slice(1).html(),
                        'airline': $(this).children('td').slice(2).html(),
                        'to': $(this).children('td').slice(3).html(),
                        'plannedArrival': $(this).children('td').slice(4).html(),
                        'realArrival': $(this).children('td').slice(5).html(),
                        'status': $(this).children('td').slice(6).html()
                    };
                }
                else {
                    flight = {
                        'date': $(this).children('td').slice(0).html(),
                        'flightNumber': $(this).children('td').slice(1).html(),
                        'airline': $(this).children('td').slice(2).html(),
                        'from': $(this).children('td').slice(3).html(),
                        'plannedArrival': $(this).children('td').slice(4).html(),
                        'realArrival': $(this).children('td').slice(5).html(),
                        'status': $(this).children('td').slice(6).html()
                    };
                }

                obj.results.push(flight);
            }
        });

        return res.cache(3600).json(obj);
    });
});
Ejemplo n.º 30
0
const lookupShip = searchStr => new Promise((resolve, reject) => {
  // Encode searchString so that Icelandic characters will work
  const searchString = encodeURIComponent(searchStr)
  const url = `http://www.samgongustofa.is/siglingar/skrar-og-utgafa/skipaskra/uppfletting?sq=${searchString}`

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      reject('www.samgongustofa.is refuses to respond or give back data')
    }

    // Translations from: https:// www.samgongustofa.is/media/siglingar/skip/Vefskipaskra-2012.pdf
    const typeDict = {
      BJÖRGUNARSKIP: 'LIFEBOAT',
      DRÁTTARSKIP: 'TUGBOAT',
      'DÝPK. OG SANDSKIP': 'DREDGERSET',
      DÝPKUNARSKIP: 'DREDGER',
      'EFTIRLITS‐ OG BJÖRGUNARSKIP': 'PATROL AND LIFEBOAT',
      FARÞEGASKIP: 'PASSENGERSHIP',
      'FISKI,FARÞEGASKIP': 'FISHING,PASSENGERSHIP',
      FISKISKIP: 'FISHING VESSEL',
      FLOTBRYGGJA: 'PONTOON BRIDGE',
      FLOTKVÍ: 'FLOATING DOCK',
      'FLUTNINGA/BRUNNSKIP': 'CARGO VESSEL LIVE FISH CARRIER',
      FRÍSTUNDAFISKISKIP: '',
      'HAFNSÖGU/DRÁTTARSKIP': 'PILOT‐ AND TUGBOAT',
      HVALVEIÐISKIP: 'FISH.V.WHALE CATCHER',
      LÓÐSSKIP: 'PILOT BOAT',
      'NÓTAVEIÐI/SKUTTOGARI': 'FISH.V.PURSE STEINERS/ST',
      OLÍUSKIP: 'OIL TANKER',
      PRAMMI: 'BARGE',
      RANNSÓKNARSKIP: 'RESEARCH VESSEL',
      SAFNSKIP: 'MUSEUM SHIP',
      SEGLSKIP: 'SAILBOAT',
      SJÓMÆLINGASKIP: '',
      SKEMMTISKIP: 'PLEASURE CRAFT',
      SKÓLASKIP: 'TRAINING VESSEL',
      SKUTTOGARI: 'FISH.V.STERN TRAWLER',
      VARÐSKIP: 'INSPECTION SHIP',
      VINNUSKIP: 'WORKBOAT',
      VÍKINGASKIP: 'VIKING SHIP',
      VÖRUFLUTNINGASKIP: 'DRY CARGO SHIP',
      ÞANGSKURÐARPRAMMI: 'BARGE',
    }

    const data = $(body)
    const fieldList = []
    data.find('.vehicleinfo ul').each((index, element) => {
      const fields = []
      $(element).find('li').each((i, el) => {
        // i === 10 is info about ship owners
        if (i !== 10) {
          const val = $(el).find('span').text()
          fields.push(val)
        } else {
          // We'll parse the owners' field separately
          const owners = []
          $(el).children('span').each(function () {
            const info = $(this).text().split(/\s{2,}/g)
            const owner = {
              name: info[1],
              socialnumber: info[2].replace('(kt. ', '').replace('-', '').replace(')', ''),
              share: parseIsFloat(info[3].replace(' eign', '')) / 100,
            }
            owners.push(owner)
          })
          fields.push(owners)
        }
      })
      if (fields.length > 0) {
        fieldList.push(fields)
      }
    })


    if (fieldList.length > 0 && fieldList[0].length > 0) {
      resolve(fieldList.map((fields) => {
        const type = typeDict[fields[1]] ? typeDict[fields[1]] : fields[1]
        const registrationStatus = fields[5] === 'Skráð' ? 'Listed' : 'Unlisted'
        return {
          name: fields[0],
          type,
          registrationNumber: fields[2],
          regionalCode: fields[3].replace(/(\(.*\))/g, '').match(/(\S.*)/g).join(' '),
          homePort: fields[4],
          registrationStatus,
          grossRegisterTonnage: parseIsFloat(fields[6]),
          grossTonnage: parseIsFloat(fields[7]),
          length: parseIsFloat(fields[8]),
          buildYear: parseInt(fields[9].split('af')[0], 10),
          buildYard: fields[9].split('af')[1].match(/(\S.*)/g).join(' '),
          owners: fields[10],
        }
      }))
    } else {
      reject(`No ship found with the query ${searchStr}`)
    }
  })
})