-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeed2facebook.py
More file actions
executable file
·184 lines (137 loc) · 5.21 KB
/
feed2facebook.py
File metadata and controls
executable file
·184 lines (137 loc) · 5.21 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import configparser
import datetime
import feedparser
import html
import os
import re
import selenium
import selenium.webdriver.firefox.options
import sentry_sdk
import sqlite3
import time
from lxml.html.clean import Cleaner
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
def tprint(*args, **kwargs):
timestamp = datetime.datetime.now(datetime.timezone.utc).strftime('[%Y-%m-%dT%H:%M:%SZ]')
print(timestamp, *args, **kwargs)
class Feed2Facebook(object):
_config = None
b = None
@property
def config(self):
if self._config is None:
home = os.environ['HOME']
f_conf = '{}/.config/feed2social/config.ini'.format(home)
self._config = configparser.ConfigParser()
self._config.read(f_conf)
return self._config
@property
def facebook_username(self):
return self._config['default']['facebook_username']
def init_browser(self):
if self.b is not None:
return
home = os.environ['HOME']
service = Service('/usr/bin/geckodriver')
options = selenium.webdriver.FirefoxOptions()
options.binary_location = '/usr/bin/firefox-esr'
options.add_argument('-headless')
# Workaround to specify profile.
# via: https://github.com/SeleniumHQ/selenium/issues/11028
options.add_argument('-profile')
options.add_argument(home + '/.mozilla/firefox-esr/selenium')
self.b = selenium.webdriver.Firefox(service=service, options=options)
def post(self, text):
self.init_browser()
b = self.b
url = 'https://www.facebook.com/{}'.format(self.facebook_username)
b.get(url)
time.sleep(1)
# click to popup
t = b.find_element(by=By.CSS_SELECTOR, value='a[aria-label] + div[role="button"][tabindex="0"]')
t.click()
time.sleep(2)
# input
t = b.find_element(by=By.CSS_SELECTOR, value='div[role="dialog"] div[role="textbox"]')
t.click()
time.sleep(1)
for c in text:
t.send_keys(c)
time.sleep(1)
# click "Next"
btn = b.find_element(by=By.CSS_SELECTOR, value='div[role="dialog"] div[aria-label="Next"]')
btn.click()
time.sleep(1)
# click "Post"
btn = b.find_element(by=By.CSS_SELECTOR, value='div[role="dialog"] div[aria-label="Post"]')
btn.click()
time.sleep(1)
def main(self, sync_only=False):
tprint('* Started.')
if sync_only:
tprint('* sync_only mode: will not post to Facebook')
home = os.environ['HOME']
f_db = '{}/.config/feed2social/feed2facebook.sqlite3'.format(home)
c = self.config
if 'sentry_sdk_url' in c['default'] and '' != c['default']['sentry_sdk_url']:
sentry_sdk_url = c['default']['sentry_sdk_url']
sentry_sdk.init(sentry_sdk_url)
feed_url = c['default']['feed_url']
feed = feedparser.parse(feed_url)
items = feed.entries
s = sqlite3.connect(f_db)
sql_insert = 'INSERT INTO entry (entry_id, created_at) VALUES (?, ?);'
sql_select = 'SELECT COUNT(*) FROM entry WHERE entry_id = ?;'
# Workaround: cannot use allow_tags=[]:
cl = Cleaner(allow_tags=['p'])
for item in reversed(items):
text = item['description']
# Print out item's id.
tprint('* item.id = {}'.format(item.id))
# Craft "text".
#
# First to remove all tags except "a" and root's "div".
text = cl.clean_html(text)
# Skip if there is "#nofb" tag.
if '#nofb' in text:
continue
# Remove root's "div".
text = text.replace('<div>', '').replace('</div>', '')
# <p> and </p>
text = text.replace('<p>', '\n').replace('</p>', '\n')
# trim
text = text.strip()
# unescape
text = html.unescape(text)
# Generate parameters.
id_str = item['id']
url = item['link']
c = s.cursor()
c.execute(sql_select, (id_str, ))
if 0 == c.fetchone()[0]:
content = '{}\n\n{}'.format(text, url)
tprint('* content = {}'.format(content))
if sync_only:
tprint('* sync_only: skipping post to Facebook')
c.execute(sql_insert, (id_str, int(time.time())))
s.commit()
continue
tprint(content)
self.post(content)
c.execute(sql_insert, (id_str, int(time.time())))
s.commit()
self.quit_browser()
def quit_browser(self):
if self.b is None:
return
self.b.quit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Sync feed to Facebook')
parser.add_argument('--sync-only', action='store_true',
help='Only sync feed to database without posting to Facebook')
args = parser.parse_args()
Feed2Facebook().main(sync_only=args.sync_only)