You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

296 lines
11 KiB

  1. import os.path
  2. import sys
  3. import feedparser
  4. from mastodon import Mastodon
  5. import json
  6. import requests
  7. import re
  8. import sqlite3
  9. import html2text
  10. import time
  11. from datetime import datetime, date, timedelta
  12. # default config location is a 'config.json' next to the script.
  13. try:
  14. filedir = os.path.dirname(os.path.abspath(__file__))
  15. if len(sys.argv) < 2:
  16. print("Using default config location: %s/config.json" % filedir)
  17. config = json.load(open(filedir+'/config.json'))
  18. else:
  19. config = json.load(open(sys.argv[1]))
  20. except:
  21. print("ERROR: Config file not found!")
  22. sys.exit(1)
  23. mastinstance = config['mastodon']['instance']
  24. mastuser = config['mastodon']['user']
  25. mastpasswd = config['mastodon']['password']
  26. twitteruser = config['sources']['twitter']['user']
  27. soupuser = config['sources']['soup']['user']
  28. dryrun = config['settings']['dryrun']
  29. days = config['settings']['days']
  30. delay = config['settings']['delay']
  31. # sqlite db to store processed tweets (and corresponding toots ids)
  32. sql = sqlite3.connect(config['settings']['databasefilepath'])
  33. db = sql.cursor()
  34. db.execute('''CREATE TABLE IF NOT EXISTS posts (srcpost text, srcuser text, mastpost text, mastuser text, mastinstance text)''')
  35. mastodon_api = None
  36. def register_app(mastuser,mastpasswd,mastinstance,mastodon_api):
  37. if mastodon_api is None:
  38. if not os.path.isfile(mastinstance+'.secret'):
  39. if Mastodon.create_app(
  40. 'metasyndicator',
  41. api_base_url='https://'+mastinstance,
  42. to_file = mastinstance+'.secret'
  43. ):
  44. print('app created on instance '+mastinstance)
  45. else:
  46. print('failed to create app on instance '+mastinstance)
  47. sys.exit(1)
  48. try:
  49. mastodon_api = Mastodon(
  50. client_id=mastinstance+'.secret',
  51. api_base_url='https://'+mastinstance
  52. )
  53. mastodon_api.log_in(
  54. username=mastuser,
  55. password=mastpasswd,
  56. scopes=['read', 'write'],
  57. to_file=mastuser+".secret"
  58. )
  59. return mastodon_api
  60. except:
  61. print("ERROR: First Login Failed!")
  62. sys.exit(1)
  63. # twitter section
  64. print('====== TWITTER ======')
  65. t = feedparser.parse('http://twitrss.me/twitter_user_to_rss/?user='+twitteruser)
  66. # start with oldest
  67. for p in reversed(t.entries):
  68. # check if this tweet has been processed
  69. db.execute(
  70. 'SELECT * FROM posts WHERE srcpost = ? AND srcuser = ? AND mastuser = ? AND mastinstance = ?',
  71. (p.id, twitteruser, mastuser, mastinstance)
  72. )
  73. last = db.fetchone()
  74. print('Processing: %s' % p.id)
  75. shouldpost = True
  76. posttime = datetime(p.published_parsed.tm_year, p.published_parsed.tm_mon, p.published_parsed.tm_mday, p.published_parsed.tm_hour, p.published_parsed.tm_min, p.published_parsed.tm_sec)
  77. if last is not None:
  78. shouldpost = False
  79. print("skip: already posted")
  80. # process only unprocessed tweets less than n days old
  81. age = datetime.now() - posttime
  82. if age > timedelta(days=days):
  83. shouldpost = False
  84. print("skip: Posting older than %s days (%s)" % (days, age) )
  85. # kill tweets with fb links with fire!
  86. if "https://www.facebook.com" in p.title or "https://m.facebook.com" in p.title:
  87. shouldpost = False
  88. print("skip: a Tweet that links to facebook? ... That's too much.")
  89. if shouldpost:
  90. print(posttime)
  91. # Create application if it does not exist
  92. mastodon_api = register_app(mastuser, mastpasswd, mastinstance, mastodon_api)
  93. c = p.title
  94. if p.author.lower() != '(@%s)' % twitteruser.lower():
  95. c = ("RT %s from Twitter:\n" % p.author[1:-1]) + c
  96. toot_media = []
  97. # get the pictures...
  98. for pic in re.finditer(r"https://pbs.twimg.com/[^ \xa0\"]*", p.summary):
  99. if (not dryrun):
  100. media = requests.get(pic.group(0))
  101. media_posted = mastodon_api.media_post(media.content, mime_type=media.headers.get('content-type'))
  102. toot_media.append(media_posted['id'])
  103. media = None
  104. else:
  105. print('Dryrun: not fetching ', pic.group(0), ' and not uploading it to mastodon')
  106. # replace t.co link by original URL
  107. m = re.search(r"http[^ \xa0]*", c)
  108. if m != None:
  109. l = m.group(0)
  110. r = requests.get(l, allow_redirects=False)
  111. if r.status_code in {301,302}:
  112. c = c.replace(l,r.headers.get('Location'))
  113. # remove pic.twitter.com links
  114. m = re.search(r"pic.twitter.com[^ \xa0]*", c)
  115. if m != None:
  116. l = m.group(0)
  117. c = c.replace(l,' ')
  118. # remove ellipsis
  119. c = c.replace('\xa0…',' ')
  120. c += '\n\nSource: %s' % p.link
  121. print(c)
  122. if (not dryrun):
  123. toot = mastodon_api.status_post(c, in_reply_to_id=None, media_ids=toot_media, sensitive=False, visibility=config['sources']['twitter']['visibility'], spoiler_text=None)
  124. print( '--> toot posted!')
  125. try:
  126. db.execute("INSERT INTO posts VALUES ( ? , ? , ? , ? , ? )", (p.id, twitteruser, toot.id, mastuser, mastinstance))
  127. sql.commit()
  128. except:
  129. print('database execution failed.')
  130. print('p.id: ', p.id)
  131. print('toot.id: ', toot.id)
  132. else:
  133. print('Dryrun: not posting toot and not adding it to database')
  134. print('waiting %s seconds ...' % delay)
  135. time.sleep(delay)
  136. print('------------------------')
  137. # soup.io section
  138. print('====== SOUP ======')
  139. h = html2text.HTML2Text()
  140. h.ignore_links = True
  141. h.ignore_images = True
  142. h.body_width = 0
  143. s = feedparser.parse('http://'+soupuser+'/rss')
  144. # start with oldest
  145. for p in reversed(s.entries):
  146. # check if this tweet has been processed
  147. db.execute(
  148. 'SELECT * FROM posts WHERE srcpost = ? AND srcuser = ? AND mastuser = ? AND mastinstance = ?',
  149. (p.id, soupuser, mastuser, mastinstance)
  150. )
  151. last = db.fetchone()
  152. print('Processing: %s' % p.id)
  153. if last is not None:
  154. shouldpost = False
  155. print("skip: already posted")
  156. # process only unprocessed tweets less than n days old
  157. shouldpost = True
  158. posttime = datetime(p.published_parsed.tm_year, p.published_parsed.tm_mon, p.published_parsed.tm_mday, p.published_parsed.tm_hour, p.published_parsed.tm_min, p.published_parsed.tm_sec)
  159. age = datetime.now() - posttime
  160. if age > timedelta(days=days):
  161. shouldpost = False
  162. print("skip: Posting older than %s days (%s)" % (days, age) )
  163. if shouldpost:
  164. # Create application if it does not exist
  165. mastodon_api = register_app(mastuser, mastpasswd, mastinstance, mastodon_api)
  166. print(p.link)
  167. j = json.loads(p.soup_attributes)
  168. # get status id and user if twitter is source
  169. tweet_id = None
  170. tweet_author = None
  171. if (isinstance(j['source'], str)):
  172. if ( j['source'].startswith('https://twitter.com/') or j['source'].startswith('https://mobile.twitter.com/')):
  173. twitterurl = j['source'].split('/')
  174. tweet_author = twitterurl[3]
  175. if ( twitterurl[4] == 'status'):
  176. tweet_id = twitterurl[5]
  177. # get all tweeted statuses
  178. print(twitteruser)
  179. db.execute('SELECT srcpost FROM posts where srcuser = ?', (twitteruser,))
  180. postedtweets = []
  181. for postedtweet in db.fetchall():
  182. postedtweets.append(postedtweet[0].split('/')[-1])
  183. # check if already tweeted
  184. if tweet_id in postedtweets:
  185. print('Already posted the Tweet: ', j['source'])
  186. else:
  187. # collect information about images
  188. pics = []
  189. accepted_filetypes = ('.jpg', '.jpeg', '.png', '.webm', '.JPG', '.JPEG', '.PNG', '.WEBM') # let's don't do mp4 for now.
  190. if (isinstance(j['source'], str) and j['source'].endswith(accepted_filetypes) ):
  191. pics.append(j['source'])
  192. elif ( 'url' in j and isinstance(j['url'], str) and j['url'].endswith(accepted_filetypes) ):
  193. pics.append(j['url'])
  194. # get the images and post them to mastadon ...
  195. toot_media = []
  196. for pic in pics:
  197. if (not dryrun):
  198. media = requests.get(pic)
  199. print(pic, ' has mimetype ', media.headers.get('content-type'))
  200. media_posted = mastodon_api.media_post(media.content, mime_type=media.headers.get('content-type'))
  201. toot_media.append(media_posted['id'])
  202. else:
  203. print('Dryrun: not fetching ', pic, ' and not uploading it to mastodon')
  204. poster = p.title.split(']')[0].strip('[')
  205. poster_text = "\n(via %s on soup.io)" % poster
  206. # remove all html stuff - python module in use only supports markdown, not pure plaintext
  207. textsrc = h.handle(p.summary_detail.value.replace("<small>", "<br><small>"))
  208. # free text from lines without visible characters
  209. cleantextsrc = ''
  210. for line in textsrc.split('\n'):
  211. line = line.strip()
  212. cleantextsrc += line + '\n'
  213. # strip newlines, reduce newlines, remove markdown bold (i know, ugly), do some clean up
  214. text = cleantextsrc.strip('\n').replace('\n\n\n','\n\n').replace('**','').replace('\\--','')
  215. # link directly to source or use soup as source.
  216. if (isinstance(j['source'], str) and j['source'] not in text):
  217. source = '\n\nSource: ' + j['source']
  218. else:
  219. source = '\n\nSource: ' + p.link
  220. # shorten text if too long
  221. maximumlegth = 500 - 1 - len(poster_text) - len(source) - 50 # 50 ... just in case (if they also count attachement url and so on)
  222. text = (text[:maximumlegth] + '…') if len(text) > maximumlegth else text
  223. # add source
  224. text += source
  225. # add soup poster
  226. text += poster_text
  227. print(text)
  228. if (not dryrun):
  229. # post toot
  230. toot = mastodon_api.status_post(text, in_reply_to_id=None, media_ids=toot_media, sensitive=False, visibility=config['sources']['soup']['visibility'], spoiler_text=None)
  231. # add entry to database
  232. if "id" in toot:
  233. db.execute("INSERT INTO posts VALUES ( ? , ? , ? , ? , ? )", (p.id, soupuser, toot.id, mastuser, mastinstance))
  234. sql.commit()
  235. print( '--> ', p.id, ' posted!')
  236. else:
  237. print('Dryrun: not posting toot and not adding it to database')
  238. print('waiting %s seconds ...' % delay)
  239. time.sleep(delay)
  240. print('------------------------')