-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContentUploader.py
189 lines (163 loc) · 7.02 KB
/
ContentUploader.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
import os
import subprocess
import sys
import time
import httplib2
import requests
from apiclient.discovery import build
from googleapiclient.errors import HttpError
from moviepy.video.VideoClip import ImageClip, ColorClip, TextClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from oauth2client import file
import config
logger = config.set_logger('ContentUploader.py')
class ContentUploader(object):
def __init__(self, name, id, result_path):
self.url = None
self.name = name
self.result_path = result_path
self.id = id
self.tags = None
self.weight = None
def upload_content(self):
logger.info('Uploading content...')
self.get_weight()
self.upload()
self.store()
time.sleep(60)
self.create_thumbnail()
self.set_thumbnail()
def upload(self):
logger.info('Uploading...')
category = 'Science & Technology'
description = self.create_description()
upload_cmd = ['youtube-upload',
'--title=' + self.name[:-4],
'--description=' + description,
'--category=' + category,
'--tags=' + self.tags,
'--playlist=Litter',
'--client-secrets=' + config.SECRET_PATH,
self.result_path]
process_output = []
try:
logger.info('Attempting to run youtube-upload...')
proc = subprocess.Popen(upload_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
entry = line.decode('utf-8')
logger.info('appending entry:' + entry)
process_output.append(entry)
proc.wait()
self.url = self.extract_url(process_output)
logger.info('resulting url: ' + self.url)
except subprocess.CalledProcessError as e:
logger.error('Error occured while attempting to run youtube-upload')
logger.error(e)
@staticmethod
def extract_url(process_output):
logger.info('Extracting url...')
yt_url_base = 'https://www.youtube.com/watch?v='
key = "Video URL:"
for entry in process_output:
if key in entry:
logger.info('Key found!')
url_start_index = entry.find(yt_url_base)
if url_start_index != -1:
url_end_index = url_start_index + len(yt_url_base) + 11
return entry[url_start_index: url_end_index]
return ""
def create_description(self):
return 'Content ID ' + str(self.id) + ' was generated by the LitterBug script in an ' \
'attempt to raise environmental awareness online.\n\n' \
'To learn more about Project Litter Bug, please ' \
'visit http://projectlitterbug.com\n\n' \
'The full source code for this project can be ' \
'found at ' \
'https://github.com/nkelton/Project-Litter-Bug\n\n\n' \
'CONTENT STATS...\n\n\n' \
'Weight: ' + str(self.weight) + ' Bytes\n\n' \
+ self.retrieve_content_lst()
def retrieve_content_lst(self):
url = self._url('/content/' + str(self.id) + '/')
response = requests.get(url, auth=config.AUTH)
if response.status_code == 200:
temp = response.json()
vid_str = self.create_content_str(temp, 'vid')
gif_str = self.create_content_str(temp, 'gif')
pic_str = self.create_content_str(temp, 'pic')
sfx_str = self.create_content_str(temp, 'sfx')
return 'Videos used:' + vid_str + 'Gifs used:' + gif_str + \
'Pictures used:' + pic_str + 'Sfx used:' + sfx_str
else:
return 'Content stats currently unavailable...'
@staticmethod
def create_content_str(data, media):
content_str = '\n'
for d in data:
if d['type'] == media:
content_str += d['url'] + '\n'
return content_str
def get_weight(self):
logger.info('Getting weight...')
if os.path.exists(self.result_path):
self.weight = os.path.getsize(self.result_path)
else:
self.weight = 0
def store(self):
logger.info('Storing data...')
url = self._url('/litter/')
task = {
'litter_id': self.id,
'title': self.name[:-4],
'url': self.url,
'weight': self.weight,
}
requests.post(url, json=task, auth=config.AUTH)
def create_thumbnail(self):
logger.info('Creating thumbnail...')
color = (255, 255, 255)
size = (1280, 720)
background = ColorClip(size, color)
logo = ImageClip(config.LOGO_PATH).set_duration(1) \
.resize(width=400, height=200) \
.set_pos(('center', 'center'))
text = TextClip(txt=str(self.id), size=(500, 500)).set_position(
('center', 'bottom'))
CompositeVideoClip([background, logo, text]).save_frame(config.THUMB_PATH)
logger.info('Thumbnail saved...')
def set_thumbnail(self):
logger.info('Setting thumbnail...')
def get_authenticated_service():
logger.info('Authenticating servie...')
flow = flow_from_clientsecrets(config.SECRET_PATH,
scope=config.YOUTUBE_READ_WRITE_SCOPE,
message=config.MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage)
return build(config.YOUTUBE_API_SERVICE_NAME, config.YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
def upload_thumbnail(youtube, video_id):
logger.info('Uploading thumbnail...')
youtube.thumbnails().set(
videoId=video_id,
media_body=config.THUMB_PATH
).execute()
youtube = get_authenticated_service()
logger.info('Attaching thumbnail to videoId: ' + self.url[-11:])
try:
upload_thumbnail(youtube, self.url[-11:])
except HttpError as e:
logger.error("Error occured setting thumbnail...")
logger.error(e.content)
else:
logger.info("Thumbnail successfully set.")
@staticmethod
def _url(path):
return config.BASE_URL + path
def set_tags(self, tags):
self.tags = tags