Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.95 KB | None | 0 0
  1. from bottle import route, request, debug, run, template, redirect
  2. import urllib2
  3. import twurl
  4. import json
  5. import sqlite3
  6. import pickle
  7.  
  8. session={'logins':0, 'user': ""}
  9. shared_archives = {}
  10.  
  11.  
  12. def checkLogin(name,password):
  13. if name==password:
  14. return True
  15. else:
  16. return False
  17.  
  18. @route('/login')
  19. def login_form():
  20. global session
  21. if session['user'] != "":
  22. return template('loggedIn2.tpl',message='Successfully logged in!',success=True,logins=session['logins'], name=session['user'])
  23. else:
  24. return template ('login.tpl')
  25.  
  26. @route('/logout')
  27. def logout():
  28. session['user'] = ""
  29. return template ('login.tpl')
  30.  
  31. @route('/checkLogin', method='post')
  32. def login_submit():
  33. global session
  34. name = request.forms.get('name')
  35. password = request.forms.get('password')
  36. if checkLogin(name, password):
  37. session['logins']=session['logins']+1
  38. session['user'] = name
  39. #return template('loggedIn2.tpl',message='Successfully logged in!',success=True,logins=session['logins'], name=name)
  40. return redirect('/')
  41. else:
  42. return template('loggedIn2.tpl',message='Unlucky! Try again.',success=False)
  43.  
  44.  
  45. def makeMenu():
  46. menu = "<a class='menuItem' href='/'>Home</a><br>"
  47. menu += "<a class='menuItem' href='/login'>Login</a><br>"
  48. connect = sqlite3.connect('twitterDB.db')
  49. cursor = connect.cursor()
  50. cursor.execute("select id, name from archives order by name asc")
  51. result = cursor.fetchall()
  52. cursor.close()
  53. connect.close()
  54. for archive in result:
  55. menu += "<a class='menuItem' href='/showArchive/" + str(archive[0]) + "'>" + archive[1] + "</a><br>"
  56.  
  57. menu += '''<form method='post' action='/addArchive'>
  58. <input type='text' name='newArchive' size='15'><br>
  59. <input type='submit' name='submit' value='New Archive'>
  60. </form>'''
  61. return menu
  62.  
  63.  
  64. def getArchiveName():
  65. connect = sqlite3.connect('twitterDB.db')
  66. cursor = connect.cursor()
  67. cursor.execute("select name from archives where id=?", (session['archiveID'],))
  68. result = cursor.fetchone()
  69. cursor.close()
  70. connect.close()
  71.  
  72. html = "Archive: " + str(result[0])
  73. html += "<br /><br /><font size='4px'>Shared with:"
  74.  
  75. archiveName = str(result[0])
  76.  
  77. if shared_archives.has_key(archiveName):
  78. for user in shared_archives[archiveName]:
  79. html += user + "<br />"
  80. else:
  81. html += "<br />No one"
  82.  
  83. html += "<form action='/shareArchive/" + archiveName + "'>"
  84. html += """<input type="text" name="user" placeholder="User to share with..." />
  85. <input type="submit" value="Share" />
  86. </form>
  87. """
  88.  
  89. return html
  90.  
  91.  
  92. @route('/shareArchive/<name>')
  93. def shareArchive(name):
  94. user = request.GET.get('user')
  95.  
  96. if shared_archives.has_key(name):
  97. shared_archives[name].append(user)
  98. else:
  99. shared_archives[name] = list([user])
  100.  
  101. return redirect('/')
  102.  
  103. def callAPI(twitter_url, parameters):
  104. url=twurl.augment(twitter_url, parameters)
  105. connection = urllib2.urlopen(url)
  106. return connection.read()
  107.  
  108. def makeArchiveDropdown():
  109. connect = sqlite3.connect('twitterDB.db')
  110. cursor = connect.cursor()
  111. cursor.execute("select id, name from archives order by name asc")
  112. result = cursor.fetchall()
  113. cursor.close()
  114. connect.close()
  115. html = "<select name='archiveID' onchange='form.submit()'>"
  116. html += "<option>Save to...</option>"
  117. for archive in result:
  118. html += "<option value='" + str(archive[0]) + "'>" + archive[1] + "</option>"
  119. html += "</select>"
  120. return html
  121.  
  122.  
  123. def replaceEntities(item, tweetHTML):
  124. hashtags = set([hashtag['text'] for hashtag in item['entities']['hashtags']])
  125. mentions = set([mention['screen_name'] for mention in item['entities']['user_mentions']])
  126.  
  127. for hashtag in hashtags:
  128. find = '#{0}'.format(hashtag)
  129. replace = '<a href="http://www.twitter.com/hashtag/{0}">#{0}</a>'.format(hashtag)
  130.  
  131. tweetHTML = tweetHTML.replace(find, replace)
  132.  
  133. for mention in mentions:
  134. find = '@{0}'.format(mention)
  135. replace = '<a href="http://www.twitter.com/{0}">@{0}</a>'.format(mention)
  136.  
  137. tweetHTML = tweetHTML.replace(find, replace)
  138.  
  139. return tweetHTML
  140.  
  141. def makeTweet(item, mode, archiveList):
  142. html, tweetHTML, links = '', item['text'], ''
  143. if mode=='myTimeline':
  144. links = "<form name='archive' method='post' action='/archive'>"
  145. links += "<input type='hidden' name='tweetID' value='" + str(item['id']) + "'>"
  146. links += archiveList
  147. links += "</form>"
  148. elif mode=='archive':
  149. links="<a href='/moveUp/" + str(item['id']) + "'>Up</a><br>" + \
  150. "<a href='/moveDown/" + str(item['id']) + "'>Down</a><br>" +\
  151. "<a href='/deleteTweet/" + str(item['id']) + "'>Delete</a>"
  152. html += "<table><tr valign='top'><td width='70'>"
  153. html += "<img src='" + item['user']['profile_image_url'] + "'></td>"
  154. html += "<td><a href='/user/" + item['user']['screen_name'] + "'>@" + item['user']['screen_name'] + "</a>"
  155. html += " (" + item['user']['name'] + ")"
  156. html += "</td></tr>"
  157. html += "<tr><td>" + links + "</td><td>" + tweetHTML + "<br>"
  158. html += "</td></tr></table><hr>"
  159. return html
  160.  
  161. def showMyTimeline():
  162. twitter_url='https://api.twitter.com/1.1/statuses/home_timeline.json'
  163. parameters = {'count':5}
  164. data = callAPI(twitter_url, parameters)
  165. js = json.loads(data)
  166. html, archives = '', makeArchiveDropdown()
  167. for item in js:
  168. html = html + makeTweet(item, 'myTimeline', archives)
  169. return html
  170.  
  171. def getTweet(id):
  172. twitter_url='https://api.twitter.com/1.1/statuses/show.json'
  173. parameters = {'id':id}
  174. data = callAPI(twitter_url, parameters)
  175. return json.loads(data)
  176.  
  177. def showStoredTweets(archiveID):
  178. connect = sqlite3.connect('twitterDB.db')
  179. cursor = connect.cursor()
  180. cursor.execute("select tweet from tweets where archiveID=? order by position asc", (archiveID,))
  181. result = cursor.fetchall()
  182. cursor.close()
  183. connect.close()
  184. html = ''
  185. for tweet in result:
  186. html = html + makeTweet(pickle.loads(tweet[0]), 'archive', '')
  187. return html
  188.  
  189. @route('/archive', method='post')
  190. def archiveTweet():
  191. global session
  192. archiveID = request.POST.get('archiveID', '').strip()
  193. tweetID = request.POST.get('tweetID', '').strip()
  194. pickledTweet = pickle.dumps(getTweet(tweetID))
  195. connect = sqlite3.connect('twitterDB.db')
  196. cursor = connect.cursor()
  197. cursor.execute("SELECT position from tweets where archiveID=? ORDER BY position DESC LIMIT 1", (session['archiveID'],))
  198. dbRow = cursor.fetchone()
  199. if dbRow is not None:
  200. nextPosition = int(dbRow[0])+1
  201. else:
  202. nextPosition = 1
  203. cursor.execute("INSERT INTO tweets (tweetID, tweet, archiveID, position) VALUES (?,?,?,?)", \
  204. (tweetID, sqlite3.Binary(pickledTweet), archiveID, nextPosition))
  205. connect.commit()
  206. cursor.close()
  207. connect.close()
  208. session['archiveID'] = archiveID
  209. html = showStoredTweets(archiveID)
  210. return template('showTweets.tpl', heading=getArchiveName(), menu=makeMenu(), html=html)
  211.  
  212.  
  213. @route('/deleteTweet/<id>')
  214. def deleteTweet(id):
  215. global session
  216. connect = sqlite3.connect('twitterDB.db')
  217. cursor = connect.cursor()
  218. cursor.execute("DELETE from tweets WHERE tweetID=? and archiveID=?", (id,session['archiveID']))
  219. connect.commit()
  220. cursor.close()
  221. connect.close()
  222. html = showStoredTweets(session['archiveID'])
  223. return template('showTweets.tpl', heading=getArchiveName(), menu=makeMenu(), html=html)
  224.  
  225. @route('/moveUp/<id>')
  226. def moveUp(id):
  227. global session
  228. connect = sqlite3.connect('twitterDB.db')
  229. cursor = connect.cursor()
  230. print "Archive is " + str(session['archiveID'])
  231. cursor.execute("SELECT position FROM tweets WHERE tweetID=? and archiveID=?", (id,session['archiveID']))
  232. position = cursor.fetchone()[0]
  233. cursor.execute("SELECT tweetID, position FROM tweets WHERE position<? and archiveID=? order by position desc limit 1", (position,session['archiveID']))
  234. dbRow = cursor.fetchone()
  235. if dbRow is not None:
  236. otherID, otherPosition = dbRow[0], dbRow[1]
  237. cursor.execute("UPDATE tweets set position=? WHERE tweetID=? and archiveID=? ", (otherPosition,id,session['archiveID']))
  238. cursor.execute("UPDATE tweets set position=? WHERE tweetID=? and archiveID=?", (position,otherID,session['archiveID']))
  239. connect.commit()
  240. cursor.close()
  241. connect.close()
  242. html = showStoredTweets(session['archiveID'])
  243. return template('showTweets.tpl', heading=getArchiveName(), menu=makeMenu(), html=html)
  244.  
  245. @route('/moveDown/<id>')
  246. def moveDown(id):
  247. html = showStoredTweets(session['archiveID'])
  248. return template('showTweets.tpl', heading=getArchiveName(), menu=makeMenu(), html=html)
  249.  
  250. @route('/showArchive/<id>')
  251. def showArchive(id):
  252. global session
  253. html = showStoredTweets(id)
  254. session['archiveID'] = id
  255. return template('showTweets.tpl', heading=getArchiveName(), menu=makeMenu(), html=html)
  256.  
  257. @route('/addArchive', method='post')
  258. def addArchive():
  259. global session
  260. newArchive = request.POST.get('newArchive', '').strip()
  261. connect = sqlite3.connect('twitterDB.db')
  262. cursor = connect.cursor()
  263. cursor.execute("INSERT into archives (name) VALUES (?)", (newArchive,))
  264. connect.commit()
  265. cursor.close()
  266. connect.close()
  267. html = showMyTimeline()
  268. return template('showTweets.tpl', heading="My timeline", menu=makeMenu(), html=html)
  269.  
  270. @route('/')
  271. def index():
  272. html = showMyTimeline()
  273. return template('showTweets.tpl', heading="My timeline", menu=makeMenu(), html=html)
  274.  
  275. def replaceEntities(item, tweetHTML):
  276. hashtags = set([hashtag['text'] for hashtag in item['entities']['hashtags']])
  277. mentions = set([mention['screen_name'] for mention in item['entities']['user_mentions']])
  278.  
  279. for hashtag in hashtags:
  280. find = '#{0}'.format(hashtag)
  281. replace = '<a href="http://www.twitter.com/hashtag/{0}">#{0}</a>'.format(hashtag)
  282.  
  283. tweetHTML = tweetHTML.replace(find, replace)
  284.  
  285. for mention in mentions:
  286. find = '@{0}'.format(mention)
  287. replace = '<a href="http://www.twitter.com/{0}">@{0}</a>'.format(mention)
  288.  
  289. tweetHTML = tweetHTML.replace(find, replace)
  290.  
  291. return tweetHTMLo
  292.  
  293. debug(True)
  294. run(reloader=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement