Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 55204bddf3
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 557 lines (424 sloc) 14.349 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
import sys
import re
import logging
import traceback

import simplejson as json

from cgi import escape
from datetime import datetime
from datetime import timedelta
from time import mktime
from time import sleep
from string import Template
from htmlentitydefs import name2codepoint
from os import environ

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.api import memcache


td = timedelta(hours=7)

allurls = re.compile(r'/(.*)')
idurls = re.compile(r'[0-9]+')
remtags = re.compile(r'<.*?>')
remspaces = re.compile(r'\s+')
se_break = re.compile('[.!?:]\s+', re.VERBOSE)
charrefpat = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?')


HTTP_DATE_FMT = "%a, %d %b %Y %H:%M:%S GMT"
ATOM_DATE = "%Y-%m-%dT%H:%M:%SZ"

homepagetext = """
<html>
<head>
<title>dlvritPlus - Unofficial Google+ User Feeds</title>
<link rel="stylesheet" type="text/css" href="/style.css">
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
</head>
<body>
<div id="gb">
<span>$countmsg</span>
<a href="http://plus.google.com/">Google+</a>
</div>
<div id="header">
<h1>dlvritPlus</h1>
<h2>Unofficial Google+ User Feeds</h2>
<span id="plusone"><g:plusone size="tall"></g:plusone></span>
</div>
<div id="content">
<div id="intro">
<h2>
Want a <span class="stress">feed</span> for your Google+ posts?
</h2>
<div id="inst">
<p>
Simply add a Google+ user number to the end of this site's URL to get an Atom feed of <em>public</em> posts.
</p>
<p>
Example: <a href="$base_url/111091089527727420853">$base_url/<strong>111091089527727420853</strong></a>
</p>
<p>
<br/>
dlvritPlus feeds are for use with <a href="http://dlvr.it/">dlvr.it</a>. Other uses of dlvitPlus feeds may be rate limited.
</p>
<p>
<small>
<em>Originally created by <a href="http://www.russellbeattie.com">Russell Beattie</a></em><br/>
You can grab the source for this app on GitHub <a href="https://github.com/signe/plusfeed">here</a>.
</small>
</p>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24604146-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
"""
homepage = Template(homepagetext)

noitemstext = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>No Public Items Found</title>
<updated>$up</updated>
<id>$base_url/$p</id>
<entry>
<title>No Public Items Found</title>
<link href="http://plus.google.com/$p"/>
<id>$base_url/$p?noitems</id>
<updated>$up</updated>
<summary>Google+ user $p has not made any posts public.</summary>
</entry>
</feed>
"""

noitems = Template(noitemstext)

ratelimittext = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Rate Limited</title>
<updated>$up</updated>
<id>$base_url/$p</id>
<entry>
<title>Rate Limited</title>
<link href="http://plus.google.com/$p"/>
<id>$base_url/$p?ratelimited</id>
<updated>$up</updated>
<summary type="html">
&lt;h1&gt;Whoops!&lt;/h1&gt;

&lt;strong&gt;You've exceeded the feed retrieval limits for this feed.&lt;/strong&gt;

&lt;div&gt;Don't worry, dlvr.it can still access and post your Google+ updates.&lt;/div&gt;

&lt;div&gt;Start using &lt;a href="http://dlvr.it"&gt;dlvr.it&lt;/a&gt; to distribute your Google+
updates to Twitter, Facebook and more. &lt;br/&gt;&lt;br/&gt;

&lt;a href="http://support.dlvr.it/entries/20312856-how-to-automatically-send-your-google-posts-to-twitter-and-facebook&gt;Details&lt;/a&gt;&lt;/div&gt;
</summary>
</entry>
</feed>
"""

ratelimit = Template(ratelimittext)


class MainPage(webapp.RequestHandler):

def get(self, p):

res = self.response
out = res.out
base_url = self.request.application_url

# Rate Limit check

if p == '':
self.doHome()
return

ip = environ['REMOTE_ADDR']
host, net = ipToNetAndHost(ip, 27)

unrestricted = False
if net == '198.145.117.96':
unrestricted = True

# Rate Limit checks
# 5 per userid, 20 per ip - per 12 hours
now = datetime.today()
upstr = now.strftime(ATOM_DATE)
if not unrestricted:
logging.debug('Beginning rate limit check for ' + str(ip))
if p != '111091089527727420853':
req_count = None
try:
req_count = memcache.incr("ratelimit:" + p)
except:
req_count = None

if req_count:
if req_count > 5:
logging.debug('rate limited - returning 403 - ' + str(p) + " __ " + str(req_count))
res.set_status(403)
out.write(ratelimit.substitute(up = upstr, p = p, base_url = base_url))
return
else:
memcache.set("ratelimit:" + p, 1, 43200)


ip = environ['REMOTE_ADDR']
req_count = None
try:
req_count = memcache.incr("ratelimit:" + ip)
except:
req_count = None

if req_count:
if req_count > 20:
logging.debug('rate limited - returning 403 - ' + str(ip) + " __ " + str(req_count))
res.set_status(403)
out.write(ratelimit.substitute(up = upstr, p = p, base_url = base_url))
return
else:
memcache.set("ratelimit:" + ip, 1, 43200)

if p == 'showall' and unrestricted:
posts = memcache.get('posts')
for k,post in sorted(posts.iteritems(), reverse=True):
out.write('<p>' + str(k) + ': <a href="' + post['permalink'] + '">Posted on ' + (post['updated'] - td).strftime('%B %d, %Y - %I:%M %p') + ' PST by ' + post['author'] + '</a> <br/>' + post['title'] + '</p>\n')
return

if p == 'reset' and unrestricted:
memcache.flush_all()
out.write('reset')
return

if idurls.match(p):

# If Modified Since check

if 'If-Modified-Since' in self.request.headers:
try:
ud = memcache.get('time_' + p)
uds = datetime.strftime(ud, HTTP_DATE_FMT)

ud = datetime.strptime(uds, HTTP_DATE_FMT)
last_seen = datetime.strptime(self.request.headers['If-Modified-Since'], HTTP_DATE_FMT)

if ud and last_seen and ud <= last_seen:
logging.debug('returning 304')
res.set_status(304)
return
except:
sys.exc_clear()

op = memcache.get(p)
if op is not None:
logging.debug('delivering from cache')
res.headers['Content-Type'] = 'application/atom+xml'
out.write(op)
return



self.doFeed(p)
return

# No matches
self.error(404)
out.write('<h1>404 Not Found</h1>')


def doHome(self):

res = self.response
out = res.out
base_url = self.request.application_url

msg = ''
list = memcache.get('list')
if list:
msg = ' Serving ' + str(len(list)) + ' feeds in the past 24 hours';

out.write(homepage.substitute(countmsg = msg, base_url = base_url))



def doFeed(self, p):

res = self.response
out = res.out

try:
logging.debug('re-requesting feed')

url = 'https://plus.google.com/_/stream/getactivities/' + p + '/?sp=[1,2,"' + p + '",null,null,null,null,"social.google.com",[]]'

result = ''

try:

result = urlfetch.fetch(url, deadline=10)

except urlfetch.Error:

try:

result = urlfetch.fetch(url, deadline=10)

except urlfetch.Error, err:
self.error(500)
out.write('<h1>500 Server Error</h1><p>' + str(err) + '</p>')
logging.error(err)
return

if result.status_code == 200:

base_url = self.request.application_url
txt = cleanGoogleJSON(result.content)

try:
obj = json.loads(txt)
except json.JSONDecodeError, err:
logging.debug('JSON Decoding Error')
self.error(500)
out.write('<h1>500 Server Error</h1><p>There was an error decoding the JSON object from Google</p>')
return

posts = obj[0][1][0]

if not posts:
#self.error(400)
#out.write('<h1>400 - No Public Items Found</h1>')
logging.debug('No public feeds found')
res.headers['Content-Type'] = 'application/atom+xml'
updated = datetime.today()
upstr = updated.strftime(ATOM_DATE)
out.write(noitems.substitute(up = upstr,
p = p,
base_url = base_url))

return


author = posts[0][3]
authorimg = 'https:' + posts[0][18]
updated = datetime.fromtimestamp(float(posts[0][5])/1000)

feed = '<?xml version="1.0" encoding="UTF-8"?>\n'
feed += '<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">\n'
feed += '<title>' + author + ' - Google+ User Feed</title>\n'
feed += '<link href="https://plus.google.com/' + p + '" rel="alternate"></link>\n'
feed += '<link href="' + base_url + '/' + p + '" rel="self"></link>\n'
feed += '<id>https://plus.google.com/' + p + '</id>\n'
feed += '<updated>' + updated.strftime(ATOM_DATE) + '</updated>\n'
feed += '<author><name>' + author + '</name></author>\n'

count = 0

for post in posts:

count = count + 1
if count > 10:
break


dt = datetime.fromtimestamp(float(post[5])/1000)
id = post[21]
permalink = "https://plus.google.com/" + post[21]

desc = ''

if post[47]:
desc = post[47]
elif post[4]:
desc = post[4]

if post[44]:
desc = desc + ' <br/><br/><a href="https://plus.google.com/' + post[44][1] + '">' + post[44][0] + '</a> originally shared this post: ';

if post[66]:

if post[66][0][1]:
if (post[66][0][3]) is None:
continue
desc = desc + ' <br/><br/><a href="' + post[66][0][1] + '">' + post[66][0][3] + '</a>'

if post[66][0][6]:
if post[66][0][6][0][1].find('image') > -1:
desc = desc + ' <p><img src="http:' + post[66][0][6][0][2] + '"/></p>'
else:
try:
desc = desc + ' <a href="' + post[66][0][6][0][8] + '">' + post[66][0][6][0][8] + '</a>'
except:
sys.exc_clear()

if desc == '':
ptitle = permalink
else:
ptitle = self.htmldecode(desc)
ptitle = remtags.sub(' ', ptitle)
ptitle = remspaces.sub(' ', ptitle)

if ptitle is None:
ptitle = u""

sentend = 75

m = se_break.split(ptitle)
if m:
sentend = len(m[0]) + 1

if sentend < 5 or sentend > 75:
sentend = 75

feed += '<entry>\n'
feed += '<title>' + escape(ptitle[:sentend]) + '</title>\n'
feed += '<link href="' + permalink + '" rel="alternate"></link>\n'
feed += '<updated>' + dt.strftime(ATOM_DATE) + '</updated>\n'
feed += '<id>tag:plus.google.com,' + dt.strftime('%Y-%m-%d') + ':/' + id + '/</id>\n'
feed += '<summary type="html">' + escape(desc) + '</summary>\n'
feed += '<content type="html">' + escape(desc) + '</content>\n'
feed += '</entry>\n'

feed += '</feed>\n'

memcache.set(p, feed, 15 * 60)
memcache.set('time_' + p, updated)

mlist = memcache.get('list')
if mlist:
if p not in mlist:
mlist.append(p)
else:
mlist = []
mlist.append(p)

memcache.set('list', mlist, 60 * 60 * 24)

res.headers['Last-Modified'] = updated.strftime(HTTP_DATE_FMT)
res.headers['Content-Type'] = 'application/atom+xml'

out.write(feed)


else:
self.error(404)
out.write('<h1>404 - Not Found</h1>')
logging.debug(p + ' Not Found')

except Exception, err:
self.error(500)
out.write('<h1>500 Server Error</h1><p>' + str(err) + '</p>')
logging.error(err)
traceback.print_exc()



def htmldecode(self, text):

if type(text) is unicode:
uchr = unichr

else:
uchr = lambda value: value > 255 and unichr(value) or chr(value)

def entitydecode(match, uchr=uchr):
entity = match.group(1)
if entity is None:
return match.group(0);
elif entity.startswith('#x'):
return uchr(int(entity[2:], 16))
elif entity.startswith('#'):
return uchr(int(entity[1:]))
elif entity in name2codepoint:
return uchr(name2codepoint[entity])
else:
return match.group(0)

return charrefpat.sub(entitydecode, text)


####

def cleanGoogleJSON(json):
instring = False
inescape = False
inlabel = False
txt = lastchar = ''

for char in json[5:]:
if not instring and re.match("\s", char):
continue

if instring:
if inescape:
txt += char
inescape = False

elif char == '\\':
txt += char
inescape = True

elif char == "\"":
txt += char
instring = False
else:
txt += char

lastchar = char
continue

if inlabel:
if char == ":":
txt += "\""
inlabel = False
txt += char
lastchar = char
continue


# Add the missing nulls
if char == "\"":
txt += char
instring = True

elif char == ",":
if lastchar == "," or lastchar == "[" or lastchar == "{":
txt += "null"
txt += char

elif char == "]" or char == "}":
if lastchar == ",":
txt += "null"
txt += char

elif re.match("\d", char):
if lastchar == "{":
txt += "\""
inlabel = True
txt += char

else:
txt += char

lastchar = char

return txt

import socket, struct
 
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('>L',socket.inet_aton(ip))[0]
 
def numToDottedQuad(n):
"convert long int to dotted quad string"
return socket.inet_ntoa(struct.pack('>L',n))
 
def makeMask(n):
"return a mask of n bits as a long integer"
return (0xffffffff << (32 - n))
 
def ipToNetAndHost(ip, maskbits):
"returns tuple (network, host) dotted-quad addresses given IP and mask size"

n = dottedQuadToNum(ip)
m = makeMask(maskbits)

host = n & m
net = n - host

return numToDottedQuad(net), numToDottedQuad(host)

application = webapp.WSGIApplication([(r'/(.*)', MainPage)],debug=True)

def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()


Something went wrong with that request. Please try again.