forked from Ibercivis/TwitterDataMining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socialstickersd
161 lines (138 loc) · 5.27 KB
/
socialstickersd
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
#!/usr/bin/python2.7
# -*- coding: UTF-8 -*-
"""
Social stickers main code
"""
import SocialStickers
import tornado, tornado.auth, tornado.web, tornado.httpserver, os, json
from tornado.options import define, options
import logging, daemon, lockfile
define ("server_port", default="8080", help="Server port")
define ("daemonize", default=False, help="Start in daemon mode")
class LoginHandler(tornado.web.RequestHandler,
tornado.auth.TwitterMixin):
"""
Manages login against twitter
"""
@tornado.web.asynchronous
def get(self):
"""
Tries user auth.
"""
if not self.get_argument("oauth_token", None):
self.authorize_redirect() # If not oauth_token, ask for it to twitter
else: # Otherwise get auth user.
self.get_authenticated_user(self.async_callback(self._on_auth))
def _on_auth(self, user):
"""
Callback for user auth
"""
self.set_secure_cookie('user_', json.dumps(user), expires_days=1)
self.redirect("/")
class ContentHandler(SocialStickers.helpers.TwitterHelpers):
"""
Main content handler.
"""
@tornado.web.asynchronous
def get(self, slug="MainPage"):
"""
Main contenthandler getter, defaulting to mainpage
"""
if slug == "MainPage":
return self.render( slug, title="SocialStickers")
elif slug == "about":
return self.render( "about" )
self.users = []
self.processed_ids = 0
self.type_ = slug.lower().strip('_') # We forbid local functions
self.user = json.loads(self.get_secure_cookie('user_'))
self.show = self.get_argument('show', 'screen_name')
self.limit = int(self.get_argument('limit', 100))
self.user_id = int(self.get_argument('user_id', False))
self.pdf = self.get_argument('pdf', False)
if self.type_ == "myself":
return self._finish(
self.build_imaged_table([self.user\
for _ in range(1, self.limit )] )
)
elif self.type_ == "myself_qr":
return self._finish(
self.build_qr_table([self.user\
for _ in range(1, self.limit )] )
)
else:
try:
path = self.application.paths[slug.lower().split('_')[0]]
except KeyError:
logging.info("Failure getting path, something may be wrong")
for key, value in self.request.arguments.items():
if type(value).__name__ == "list":
self.request.arguments[key] = ','.join(value)
self.twitter_call(path)
def twitter_call(self, path):
"""
Makes a call to the twitter API and returns it to
the callback defined by the type_ property of this class
"""
self.twitter_request(
path,
self.async_callback(getattr(self, self.type_)),
self.user["access_token"],
**self.request.arguments
)
class Application(tornado.web.Application):
"""
Main tornado application for socialstickers
"""
def __init__(self):
"""
Set up handlers, paths and qr magic
"""
handlers = [
(r"/([^/]+)", ContentHandler ),
(r"/", ContentHandler ),
(r"/auth/login", LoginHandler ),
]
self.paths = {
"lists" : "/lists/memberships",
"list" : "/lists/members",
"usertimeline" : "/statuses/user_timeline",
"user_lookup" : "/users/lookup",
"showuser" : "/users/show",
"search": "/search",
"friends" : "/friends/ids",
"followers" : "/followers/ids"
}
self.qr_key_mappings = { 'url' : 'URL', 'screen_name' : 'NICKNAME', 'text' : 'NOTE', 'name' : 'N', }
self.enabled_qrcode_values = [ 'url', 'screen_name', 'name', 'text' ]
settings = dict(
cookie_secret = "43oETzaXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
login_url = "/auth/login",
template_path=os.path.join(SocialStickers.data_dir, "templates"),
static_path=os.path.join(SocialStickers.data_dir, "static"),
twitter_consumer_key = "f3hsGryVPmoO6bxm7J1CvA",
twitter_consumer_secret =\
"k94Ly8RsVeGKjyz6QjAKO2htuc8lN1VERUjaJUc9Dys",
xsrf_cookies = True,
autoescape = "xhtml_escape",
)
tornado.web.Application.__init__(self, handlers, **settings)
def do_main_program():
__server__ = tornado.httpserver.HTTPServer(Application())
__server__.listen(int(options.server_port))
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
tornado.options.parse_command_line()
if options.daemonize:
log_file = 'socialstickers.%s.log' % options.server_port
log = open(os.path.join('/var/log', log_file), 'a+')
with daemon.DaemonContext(
working_directory='/var/lib/socialstickers',
umask=0o002,
pidfile=lockfile.FileLock('/var/run/socialstickers.pid'),
stdout=log,
stderr=log
):
do_main_program()
else:
do_main_program()