Skip to content

Instantly share code, notes, and snippets.

@ryonsherman
Last active August 29, 2015 13:58
Show Gist options
  • Save ryonsherman/d30944ffc73e9c44426a to your computer and use it in GitHub Desktop.
Save ryonsherman/d30944ffc73e9c44426a to your computer and use it in GitHub Desktop.
Tomorrow at a glance
#!/usr/bin/env php
<?php
if (!count(debug_backtrace())) {
$script = new Script();
print date('l', $script->date).": ".
html_entity_decode("[temp 0&deg;:0&deg;:%] ").
"[sun {$script->sun->rise}-{$script->sun->set}]".
"\n";
}
class Script {
public $ip;
public $loc;
public $sun;
public $date;
private $cache;
public function __construct() {
$this->id = trim(shell_exec('hostid'));
$this->date = $this->get_date();
$this->cache = $this->_get_cached_data();
$this->ip = $this->get_ip();
$this->loc = $this->get_loc();
$this->sun = $this->get_sun();
$this->_set_cached_data();
}
private function _set_cached_data() {
$data = json_encode($this->cache);
$query = "http://query.yahooapis.com/v1/public/yql?q=" . rawurlencode(trim("
select * from yahoo.caching where cache_key = '{$this->id}_{$this->date}' and cache_value = '{$data}' and put = '1'
"));
file_get_contents($query);
}
private function _get_cached_data() {
$query = "http://query.yahooapis.com/v1/public/yql?q=" . rawurlencode(trim("
select * from yahoo.caching where cache_key = '{$this->id}_{$this->date}' and get = '1'
")) . "&format=json";
$this->_data = json_decode(file_get_contents($query))->query->results->result ?: false;
return json_decode($this->_data) ?: false;
}
public function get_date() {
$now = strtotime('now');
return strtotime((strtotime('today 00:00') < $now and $now < strtotime('today 17:00')) ? 'today' : 'tomorrow');
}
public function get_ip() {
if ($ip = $this->ip) return $ip;
if ($ip = $this->cache->ip) return $ip;
return $this->ip = $this->cache->ip = trim(file_get_contents("http://ifconfig.me/ip"));
}
public function get_loc() {
if (@$this->loc->lat) return $this->loc;
if (@$this->cache->location->lat) return $this->loc = $this->cache->location;
$data = json_decode(trim(file_get_contents("http://freegeoip.net/json/{$this->ip}")));
foreach (get_object_vars($data) as $key => $value) {
$this->cache->{$key} = $value;
}
return $this->loc = $this->cache->location = json_decode(json_encode(array('lat' => @$this->cache->latitude, 'lon' => @$this->cache->longitude)), false);
}
public function get_sun() {
if (@$this->sun->rise) return $this->sun;
if (@$this->cache->sun->rise) return $this->sun = $this->cache->sun;
list($day, $month, $tz, $dst) = explode(',', date('j,n,Z,I', $this->date));
$tz /= 60;
$data = simplexml_load_string(trim(file_get_contents("http://www.earthtools.org/sun/{$this->loc->lat}/{$this->loc->lon}/{$day}/{$month}/{$tz}/{$dst}")));
$sunrise = date('G:i:s', strtotime(@$data->morning->sunrise) + ($tz * 60 - ($dst * 3600)));
$sunset = date('G:i:s', strtotime(@$data->evening->sunset) + ($tz * 60 - ($dst * 3600)));
return $this->sun = $this->cache->sun = json_decode(json_encode(array('rise' => $sunrise, 'set' => $sunset)));
}
}
?>
#!/usr/bin/env python2
from time import strftime
from json import loads, dumps
from urllib import urlencode
from urllib2 import urlopen
from hashlib import sha1
from xml.dom import minidom
from dateutil import parser
from subprocess import PIPE, Popen
class Script:
def __init__(self):
#self.ip = self.get_ip()
self.host = self._get_host()
key = sha1("{}{}{}".format(self.ip, self.host, strftime("%Y%m%d%H"))).hexdigest()
self.cache = self._get_cache(key)
self.loc = self.get_loc()
self.date = self.get_date()
print self.date
self._set_cache(key)
def _request(self, url):
return urlopen(url).read().strip()
def _set_cache(self, key):
data = dumps(self.cache)
print "Set", self.cache
query = "select * from yahoo.caching where cache_key = '{}' and cache_value = '{}' and put = '1'".format(key, data)
params = urlencode({'q': query, 'format': 'json'})
url = "http://query.yahooapis.com/v1/public/yql?{}".format(params)
self._request(url)
def _get_cache(self, key):
query = "select * from yahoo.caching where cache_key = '{}' and get = '1'".format(key)
params = urlencode({'q': query, 'format': 'json'})
url = "http://query.yahooapis.com/v1/public/yql?{}".format(params)
try:
self.cache = loads(loads(self._request(url))['query']['results']['result'])
except TypeError, KeyError:
self.cache = {}
print "Got", self.cache
return self.cache
def _get_host(self):
return Popen('hostid', stdout=PIPE).stdout.read().strip()
def get_ip(self):
if getattr(self, 'ip', False): return self.ip
self.ip = self._request("http://ifconfig.me/ip")
return self.ip
def get_loc(self):
if getattr(self, 'loc', False): return self.loc
if 'loc' in self.cache and self.cache['loc']: return self.cache['loc']
data = loads(self._request("http://freegeoip.net/json/{}".format(self.ip)))
self.cache.update(data)
self.loc = self.cache[u'loc'] = {u'lat': unicode(data['latitude']), u'lon': unicode(data['longitude'])}
return self.loc
def get_date(self):
if getattr(self, 'date', False): return self.date
if 'date' in self.cache and self.cache['date']:
self.date = parser.parse(self.cache['date'])
return self.date
url = "http://www.earthtools.org/timezone/{}/{}".format(*self.loc.values())
xml = minidom.parseString(self._request(url)).getElementsByTagName('timezone')[0]
self.cache[u'date'] = unicode(xml.getElementsByTagName('isotime')[0].firstChild.nodeValue)
self.date = parser.parse(self.cache['date'])
return self.date
def get_weather(self):
# http://forecast.weather.gov/MapClick.php?lat=40.78158&lon=-73.96648&FcstType=dwml
pass
def get_sunlight(self):
#http://www.earthtools.org/sun/40.71417/-74.00639/4/12/-5/0
pass
if __name__ == '__main__':
data = Script().cache
print u"Tomorrow it will be {condition} in {city}, {state} from {sunrise} until {sunset}, " \
"temperatures between {low} {degree}{temp} and {high} {degree}{temp}, " \
"and a {percent}% chance of {precip}.".format(
condition="{condition}",
city=data['city'],
state=data['region_code'],
sunrise="{sunrise}",
sunset="{sunset}",
low="{low}",
high="{high}",
degree=u"\N{DEGREE SIGN}",
temp="{temp}",
percent="{percent}",
precip="{precip}"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment