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.
 
 

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