2018-10-08 18:11:51 -07:00
#!/usr/bin/env python3
2018-10-24 19:37:11 -07:00
# toot downloader version two!!
2018-10-08 18:11:51 -07:00
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from mastodon import Mastodon
from os import path
from bs4 import BeautifulSoup
2019-08-06 20:46:57 -07:00
import os , sqlite3 , signal , sys , json , re , shutil , argparse
2018-10-24 19:37:11 -07:00
import requests
2019-01-11 04:58:17 -08:00
import functions
2018-10-08 18:11:51 -07:00
2019-08-06 20:46:57 -07:00
parser = argparse . ArgumentParser ( description = ' Log in and download posts. ' )
2019-08-06 20:48:45 -07:00
parser . add_argument ( ' -c ' , ' --cfg ' , dest = ' cfg ' , default = ' config.json ' , nargs = ' ? ' ,
2019-08-06 20:46:57 -07:00
help = " Specify a custom location for config.json. " )
args = parser . parse_args ( )
2019-05-19 05:31:42 -07:00
scopes = [ " read:statuses " , " read:accounts " , " read:follows " , " write:statuses " , " read:notifications " , " write:accounts " ]
2019-04-28 20:59:37 -07:00
#cfg defaults
2019-05-19 05:31:42 -07:00
2019-04-28 20:59:37 -07:00
cfg = {
" site " : " https://botsin.space " ,
" cw " : None ,
2019-08-06 20:46:57 -07:00
" instance_blacklist " : [ " bofa.lol " , " witches.town " , " knzk.me " ] , # rest in piece
2019-04-28 21:24:52 -07:00
" learn_from_cw " : False ,
" mention_handling " : 1 ,
2019-07-01 00:19:52 -07:00
" max_thread_length " : 15 ,
" strip_paired_punctuation " : False
2019-04-28 20:59:37 -07:00
}
2019-05-19 05:31:42 -07:00
2019-08-13 22:00:35 -07:00
try :
cfg . update ( json . load ( open ( args . cfg , ' r ' ) ) )
except FileNotFoundError :
open ( args . cfg , " w " ) . write ( " {} " )
2019-08-06 20:46:57 -07:00
print ( " Using {} as configuration file " . format ( args . cfg ) )
2019-01-11 04:05:29 -08:00
2018-10-24 19:37:11 -07:00
if " client " not in cfg :
2019-01-11 04:08:10 -08:00
print ( " No application info -- registering application with {} " . format ( cfg [ ' site ' ] ) )
2018-10-24 19:37:11 -07:00
client_id , client_secret = Mastodon . create_app ( " mstdn-ebooks " ,
api_base_url = cfg [ ' site ' ] ,
scopes = scopes ,
website = " https://github.com/Lynnesbian/mstdn-ebooks " )
cfg [ ' client ' ] = {
" id " : client_id ,
" secret " : client_secret
}
if " secret " not in cfg :
2019-01-11 04:08:10 -08:00
print ( " No user credentials -- logging in to {} " . format ( cfg [ ' site ' ] ) )
2018-10-24 19:37:11 -07:00
client = Mastodon ( client_id = cfg [ ' client ' ] [ ' id ' ] ,
client_secret = cfg [ ' client ' ] [ ' secret ' ] ,
api_base_url = cfg [ ' site ' ] )
2018-10-08 18:11:51 -07:00
2019-01-11 04:08:10 -08:00
print ( " Open this URL and authenticate to give mstdn-ebooks access to your bot ' s account: {} " . format ( client . auth_request_url ( scopes = scopes ) ) )
2018-10-24 19:37:11 -07:00
cfg [ ' secret ' ] = client . log_in ( code = input ( " Secret: " ) , scopes = scopes )
2018-10-08 18:11:51 -07:00
2019-08-06 20:46:57 -07:00
json . dump ( cfg , open ( args . cfg , " w+ " ) )
2018-10-08 18:11:51 -07:00
2018-10-24 19:37:11 -07:00
def extract_toot ( toot ) :
2019-01-11 04:58:17 -08:00
toot = functions . extract_toot ( toot )
2018-11-27 03:29:50 -08:00
toot = toot . replace ( " @ " , " @ \u200B " ) #put a zws between @ and username to avoid mentioning
2018-10-24 19:37:11 -07:00
return ( toot )
2018-10-08 18:11:51 -07:00
client = Mastodon (
2018-10-24 19:37:11 -07:00
client_id = cfg [ ' client ' ] [ ' id ' ] ,
2019-02-25 10:30:40 -08:00
client_secret = cfg [ ' client ' ] [ ' secret ' ] ,
access_token = cfg [ ' secret ' ] ,
2018-10-24 19:37:11 -07:00
api_base_url = cfg [ ' site ' ] )
2018-10-08 18:11:51 -07:00
me = client . account_verify_credentials ( )
following = client . account_following ( me . id )
db = sqlite3 . connect ( " toots.db " )
db . text_factory = str
c = db . cursor ( )
2019-08-13 22:17:38 -07:00
c . execute ( " CREATE TABLE IF NOT EXISTS `toots` (sortid INT NOT NULL DEFAULT 0, id VARCHAR NOT NULL UNIQUE PRIMARY KEY, cw INT NOT NULL DEFAULT 0, userid VARCHAR NOT NULL, uri VARCHAR NOT NULL, content VARCHAR NOT NULL) WITHOUT ROWID " )
2019-02-24 17:17:06 -08:00
try :
2019-08-13 22:17:38 -07:00
c . execute ( " ALTER TABLE `toots` ADD COLUMN sortid INT NOT NULL DEFAULT 0 " )
for f in following :
last_toot = c . execute ( " SELECT id FROM `toots` WHERE userid LIKE ? ORDER BY id DESC LIMIT 1 " , ( f . id , ) ) . fetchone ( )
if last_toot != None :
last_toot = last_toot [ 0 ]
else :
last_toot = 0
c . execute ( " UPDATE `toots` SET sortid = 1 WHERE id LIKE ? AND userid LIKE ? " , ( last_toot , f . id ) )
2019-02-24 17:17:06 -08:00
except :
pass # column already exists
2018-10-08 18:11:51 -07:00
db . commit ( )
2019-08-13 22:17:38 -07:00
sys . exit ( 0 )
2018-10-08 18:11:51 -07:00
def handleCtrlC ( signal , frame ) :
print ( " \n PREMATURE EVACUATION - Saving chunks " )
db . commit ( )
sys . exit ( 1 )
signal . signal ( signal . SIGINT , handleCtrlC )
2019-02-07 07:27:52 -08:00
patterns = {
2019-02-07 07:45:44 -08:00
" handle " : re . compile ( r " ^.*@(.+) " ) ,
" url " : re . compile ( r " https?: \ / \ /(.*) " ) ,
" uri " : re . compile ( r ' template= " ([^ " ]+) " ' ) ,
" pid " : re . compile ( r " [^ \ /]+$ " ) ,
2019-02-07 07:27:52 -08:00
}
2018-10-27 01:28:20 -07:00
2019-02-25 10:30:40 -08:00
2019-08-13 22:17:38 -07:00
def insert_toot ( oii , acc , post , cursor ) : # extracted to prevent duplication
2019-02-25 10:30:40 -08:00
pid = patterns [ " pid " ] . search ( oii [ ' object ' ] [ ' id ' ] ) . group ( 0 )
cursor . execute ( " REPLACE INTO toots (id, cw, userid, uri, content) VALUES (?, ?, ?, ?, ?) " , (
pid ,
1 if ( oii [ ' object ' ] [ ' summary ' ] != None and oii [ ' object ' ] [ ' summary ' ] != " " ) else 0 ,
acc . id ,
oii [ ' object ' ] [ ' id ' ] ,
post
) )
2018-10-08 18:11:51 -07:00
for f in following :
last_toot = c . execute ( " SELECT id FROM `toots` WHERE userid LIKE ? ORDER BY id DESC LIMIT 1 " , ( f . id , ) ) . fetchone ( )
if last_toot != None :
last_toot = last_toot [ 0 ]
else :
last_toot = 0
2019-05-19 06:06:31 -07:00
print ( " Downloading posts for user @ {} , starting from {} " . format ( f . acct , last_toot ) )
2018-10-24 19:37:11 -07:00
#find the user's activitypub outbox
2019-02-24 17:18:38 -08:00
print ( " WebFingering... " )
2019-02-07 07:45:44 -08:00
instance = patterns [ " handle " ] . search ( f . acct )
2018-10-24 19:37:11 -07:00
if instance == None :
2019-02-07 07:45:44 -08:00
instance = patterns [ " url " ] . search ( cfg [ ' site ' ] ) . group ( 1 )
2018-10-24 19:37:11 -07:00
else :
instance = instance . group ( 1 )
2019-01-11 05:08:53 -08:00
if instance in cfg [ ' instance_blacklist ' ] :
print ( " skipping blacklisted instance: {} " . format ( instance ) )
2018-10-25 07:33:57 -07:00
continue
2019-01-11 04:15:05 -08:00
2018-10-24 19:37:11 -07:00
try :
2019-06-30 18:21:08 -07:00
# 1. download host-meta to find webfinger URL
2018-10-27 05:07:38 -07:00
r = requests . get ( " https:// {} /.well-known/host-meta " . format ( instance ) , timeout = 10 )
2019-05-19 06:06:31 -07:00
# 2. use webfinger to find user's info page
2019-02-07 07:45:44 -08:00
uri = patterns [ " uri " ] . search ( r . text ) . group ( 1 )
2018-10-24 19:37:11 -07:00
uri = uri . format ( uri = " {} @ {} " . format ( f . username , instance ) )
2018-10-27 05:07:38 -07:00
r = requests . get ( uri , headers = { " Accept " : " application/json " } , timeout = 10 )
2018-10-27 01:28:20 -07:00
j = r . json ( )
2019-05-19 06:06:31 -07:00
found = False
2019-02-06 16:53:23 -08:00
for link in j [ ' links ' ] :
if link [ ' rel ' ] == ' self ' :
#this is a link formatted like "https://instan.ce/users/username", which is what we need
uri = link [ ' href ' ]
2019-05-19 06:06:31 -07:00
found = True
break
if not found :
print ( " Couldn ' t find a valid ActivityPub outbox URL. " )
# 3. download first page of outbox
2018-11-06 21:39:12 -08:00
uri = " {} /outbox?page=true " . format ( uri )
2019-05-19 06:06:31 -07:00
r = requests . get ( uri , timeout = 15 )
2018-10-24 19:37:11 -07:00
j = r . json ( )
2019-05-19 06:06:31 -07:00
except :
2018-10-24 19:37:11 -07:00
print ( " oopsy woopsy!! we made a fucky wucky!!! \n (we ' re probably rate limited, please hang up and try again) " )
sys . exit ( 1 )
2018-10-27 01:28:20 -07:00
pleroma = False
2019-05-19 06:06:31 -07:00
if ' next ' not in j :
print ( " Using Pleroma compatibility mode " )
2018-10-27 01:28:20 -07:00
pleroma = True
2018-11-06 21:39:12 -08:00
j = j [ ' first ' ]
2018-11-09 03:49:33 -08:00
else :
2019-05-19 06:06:31 -07:00
print ( " Using standard mode " )
2018-11-09 03:49:33 -08:00
uri = " {} &min_id= {} " . format ( uri , last_toot )
2018-11-06 21:39:12 -08:00
r = requests . get ( uri )
j = r . json ( )
2019-05-19 06:06:31 -07:00
print ( " Downloading and saving posts " , end = ' ' , flush = True )
2018-11-06 21:39:12 -08:00
done = False
2018-11-09 03:50:36 -08:00
try :
2018-11-06 21:39:12 -08:00
while not done and len ( j [ ' orderedItems ' ] ) > 0 :
for oi in j [ ' orderedItems ' ] :
2018-11-28 11:36:05 -08:00
if oi [ ' type ' ] != " Create " :
2019-01-11 04:15:05 -08:00
continue #this isn't a toot/post/status/whatever, it's a boost or a follow or some other activitypub thing. ignore
2019-02-25 10:30:40 -08:00
2018-11-28 11:36:05 -08:00
# its a toost baby
content = oi [ ' object ' ] [ ' content ' ]
toot = extract_toot ( content )
# print(toot)
try :
if pleroma :
2018-12-29 15:58:43 -08:00
if c . execute ( " SELECT COUNT(*) FROM toots WHERE uri LIKE ? " , ( oi [ ' object ' ] [ ' id ' ] , ) ) . fetchone ( ) [ 0 ] > 0 :
2018-11-28 11:36:05 -08:00
#we've caught up to the notices we've already downloaded, so we can stop now
2019-05-06 10:05:02 -07:00
#you might be wondering, "lynne, what if the instance ratelimits you after 40 posts, and they've made 60 since main.py was last run? wouldn't the bot miss 20 posts and never be able to see them?" to which i reply, "i know but i don't know how to fix it"
2018-11-28 11:36:05 -08:00
done = True
2019-07-09 17:43:56 -07:00
if ' lang ' in cfg :
2019-05-06 10:14:30 -07:00
try :
2019-05-19 06:06:31 -07:00
if oi [ ' object ' ] [ ' contentMap ' ] [ cfg [ ' lang ' ] ] : # filter for language
2019-05-06 10:14:30 -07:00
insert_toot ( oi , f , toot , c )
except KeyError :
#JSON doesn't have contentMap, just insert the toot irregardlessly
2019-02-25 10:30:40 -08:00
insert_toot ( oi , f , toot , c )
else :
insert_toot ( oi , f , toot , c )
2018-11-28 11:36:05 -08:00
pass
except :
pass #ignore any toots that don't successfully go into the DB
2019-05-19 06:06:31 -07:00
# get the next/previous page
try :
if not pleroma :
r = requests . get ( j [ ' prev ' ] , timeout = 15 )
else :
r = requests . get ( j [ ' next ' ] , timeout = 15 )
except requests . Timeout :
print ( " HTTP timeout, site did not respond within 15 seconds " )
except :
print ( " An error occurred while trying to obtain more posts. " )
2018-11-06 21:39:12 -08:00
j = r . json ( )
print ( ' . ' , end = ' ' , flush = True )
2018-10-24 19:37:11 -07:00
print ( " Done! " )
db . commit ( )
2019-05-06 10:02:42 -07:00
except requests . HTTPError as e :
if e . response . status_code == 429 :
print ( " Rate limit exceeded. This means we ' re downloading too many posts in quick succession. Saving toots to database and moving to next followed account. " )
db . commit ( )
else :
# TODO: remove duplicate code
2019-05-19 06:06:31 -07:00
print ( " Encountered an error! Saving posts to database and moving to next followed account. " )
2019-05-06 10:02:42 -07:00
db . commit ( )
2018-11-09 03:50:36 -08:00
except :
2019-05-19 06:06:31 -07:00
print ( " Encountered an error! Saving posts to database and moving to next followed account. " )
2018-11-09 03:50:36 -08:00
db . commit ( )
2018-10-31 22:27:03 -07:00
print ( " Done! " )
2018-10-08 18:11:51 -07:00
db . commit ( )
db . execute ( " VACUUM " ) #compact db
db . commit ( )
2018-12-29 15:58:43 -08:00
db . close ( )