-
Notifications
You must be signed in to change notification settings - Fork 1
/
TweetPinnaImageDownloader.py
203 lines (163 loc) · 6.66 KB
/
TweetPinnaImageDownloader.py
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""TweetPinna - Twitter Status Archiver.
TweetPinna streams Twitter statuses into a
MongoDB database based on given search terms.
It is also capable of retrieving a user's timeline.
This script downloads image data found in tweets for further analysis.
Author: Ingo Kleiber <ingo@kleiber.me> (2017)
License: MIT
Version: 1.1.1
Status: Protoype
Example:
$ python TweetPinnaImageDownloader.py config.cfg (objectId)
"""
from bson.objectid import ObjectId
from pymongo import MongoClient
from TweetPinna import check_config
from TweetPinna import Logger
import config
import datetime
import mimetypes
import os.path
import requests
import signal
import sys
from urllib.parse import urlparse
from urllib.parse import urlsplit
import shutil
try:
if os.path.isfile(sys.argv[1]):
if check_config(sys.argv[1]):
cfg = config.Config(open(sys.argv[1], 'r'))
log = Logger(cfg)
else:
print('Configuration appears to be faulty')
sys.exit(1)
else:
print('Configuration file {} could not be found'.format(sys.argv[1]))
sys.exit(1)
except IndexError:
print('Using default configuration')
cfg = config.Config(open('cfg/TweetPinnaDefault.cfg', 'r'))
log = Logger(cfg)
# Create directories
if not os.path.exists(cfg['media_photo_storage']):
os.makedirs(cfg['media_photo_storage'])
if not os.path.exists(cfg['media_user_storage']):
os.makedirs(cfg['media_user_storage'])
def signal_handler(signum, frame):
"""Handlig interrupt signals."""
sys.exit(1)
def get_file_extension(url):
"""Getting the extensions (filetype) of an url.
:param str url: the url to the file
"""
filetype = os.path.splitext(
os.path.basename(
urlsplit(url).path))[1]
return filetype
def download_media_file(type, url, filename, filetype='', copy_to=''):
"""Downloading a media file.
:param str type: the type of the file (photo, user-profile-img,
user-banner-img, user-bg-img)
:param str url: the url to download from
:param str filename: the filename to save to
:param str filetype: the filytype (optional)
:param str copy_to: a folder to which a copy of the file is sent
"""
if (len(url) > 0):
try:
if type == 'photo':
path = cfg['media_photo_storage'] + filename
elif type in (
'user-profile-img', 'user-banner-img', 'user-bg-img'):
path = cfg['media_user_storage'] + filename
else:
return False
if not os.path.exists(path):
r = requests.get(url, stream=True)
if not filetype:
try:
path = path + mimetypes.guess_extension(
r.headers['content-type'])
except:
path = path + '.unknown'
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
if copy_to:
shutil.copy2(path, copy_to)
except Exception as e:
log.log_add(3, 'Image download failed ({})'.format(e))
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal_handler)
# MongoDB
mongo_client = MongoClient(cfg['mongo_path'])
mongo_db = mongo_client[cfg['mongo_db']]
mongo_coll_tweets = mongo_db[cfg['mongo_coll']]
# Whole collections vs. individual ObjectId
try:
search_object_id = sys.argv[2]
except:
search_object_id = False
if search_object_id:
try:
tweets = mongo_coll_tweets.find({'_id': ObjectId(sys.argv[2])})
except:
print('ObjectId seems to be invalid')
sys.exit(1)
if tweets.count() < 1:
print('ObjectId not found')
sys.exit(1)
else:
tweets = mongo_coll_tweets.find()
# Download
number_tweets = tweets.count()
current_count = 0
for tweet in tweets:
if current_count % 100 == 0:
print ('{} of {} Tweets processed'.format(current_count,
number_tweets))
object_id = tweet["_id"]
tweet_timestamp_s = int(tweet["timestamp_ms"]) / 1000
tweet_date = datetime.datetime.fromtimestamp(
tweet_timestamp_s).strftime('%Y%m%d')
tweet_id = int(tweet["id"])
user_id = tweet["user"]["id"]
print(tweet_id)
if "profile_image_url" in tweet["user"]:
user_profile_image_url = tweet["user"]["profile_image_url"]
if cfg['media_profile_image_hd'] == 1:
user_profile_image_url = user_profile_image_url.replace(
'normal', '400x400')
filetype = get_file_extension(user_profile_image_url)
download_media_file(
'user-profile-img', user_profile_image_url, '{}-profile-{}{}'.
format(user_id, tweet_date, filetype), filetype)
if "profile_banner_url" in tweet["user"]:
user_profile_banner_url = tweet["user"]["profile_banner_url"]
filetype = get_file_extension(user_profile_banner_url)
download_media_file(
'user-banner-img', user_profile_banner_url, '{}-banner-{}{}'.
format(user_id, tweet_date, filetype), filetype)
if "profile_background_image_url" in tweet["user"]:
user_profile_bg_url = tweet["user"]["profile_background_image_url"]
filetype = get_file_extension(user_profile_bg_url)
download_media_file(
'user-bg-img', user_profile_bg_url, '{}-bg-{}{}'.
format(user_id, tweet_date, filetype), filetype)
if "media" in tweet["entities"]:
for media in tweet["entities"]["media"]:
media_id = media["id"]
if media["type"] == "photo":
photo_url = media["media_url_https"]
filetype = get_file_extension(photo_url)
download_media_file(
'photo', photo_url, '{0}-{1}-{2}{3}'.format(object_id,
tweet_id,
media_id,
filetype),
filetype)
current_count += 1