main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #!/usr/bin/env python
  2. #
  3. # Upload videos to Youtube from the command-line using APIv3.
  4. #
  5. # Author: Arnau Sanchez <pyarnau@gmail.com>
  6. # Project: https://github.com/tokland/youtube-upload
  7. """
  8. Upload a video to Youtube from the command-line.
  9. $ youtube-upload --title="A.S. Mutter playing" \
  10. --description="Anne Sophie Mutter plays Beethoven" \
  11. --category=Music \
  12. --tags="mutter, beethoven" \
  13. anne_sophie_mutter.flv
  14. pxzZ-fYjeYs
  15. """
  16. import os
  17. import sys
  18. import optparse
  19. import collections
  20. import webbrowser
  21. import googleapiclient.errors
  22. import oauth2client
  23. from . import auth
  24. from . import upload_video
  25. from . import categories
  26. from . import lib
  27. from . import playlists
  28. # http://code.google.com/p/python-progressbar (>= 2.3)
  29. try:
  30. import progressbar
  31. except ImportError:
  32. progressbar = None
  33. class InvalidCategory(Exception): pass
  34. class OptionsError(Exception): pass
  35. class AuthenticationError(Exception): pass
  36. class RequestError(Exception): pass
  37. EXIT_CODES = {
  38. OptionsError: 2,
  39. InvalidCategory: 3,
  40. RequestError: 3,
  41. AuthenticationError: 4,
  42. oauth2client.client.FlowExchangeError: 4,
  43. NotImplementedError: 5,
  44. }
  45. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  46. debug = lib.debug
  47. struct = collections.namedtuple
  48. def open_link(url):
  49. """Opens a URL link in the client's browser."""
  50. webbrowser.open(url)
  51. def get_progress_info():
  52. """Return a function callback to update the progressbar."""
  53. progressinfo = struct("ProgressInfo", ["callback", "finish"])
  54. if progressbar:
  55. bar = progressbar.ProgressBar(widgets=[
  56. progressbar.Percentage(),
  57. ' ', progressbar.Bar(),
  58. ' ', progressbar.FileTransferSpeed(),
  59. ' ', progressbar.DataSize(), '/', progressbar.DataSize('max_value'),
  60. ' ', progressbar.Timer(),
  61. ' ', progressbar.AdaptiveETA(),
  62. ])
  63. def _callback(total_size, completed):
  64. if not hasattr(bar, "next_update"):
  65. if hasattr(bar, "maxval"):
  66. bar.maxval = total_size
  67. else:
  68. bar.max_value = total_size
  69. bar.start()
  70. bar.update(completed)
  71. def _finish():
  72. if hasattr(bar, "next_update"):
  73. return bar.finish()
  74. return progressinfo(callback=_callback, finish=_finish)
  75. else:
  76. return progressinfo(callback=None, finish=lambda: True)
  77. def get_category_id(category):
  78. """Return category ID from its name."""
  79. if category:
  80. if category in categories.IDS:
  81. ncategory = categories.IDS[category]
  82. debug("Using category: {0} (id={1})".format(category, ncategory))
  83. return str(categories.IDS[category])
  84. else:
  85. msg = "{0} is not a valid category".format(category)
  86. raise InvalidCategory(msg)
  87. def upload_youtube_video(youtube, options, video_path, total_videos, index):
  88. """Upload video with index (for split videos)."""
  89. u = lib.to_utf8
  90. title = u(options.title)
  91. if hasattr(u('string'), 'decode'):
  92. description = u(options.description or "").decode("string-escape")
  93. else:
  94. description = options.description
  95. if options.publish_at:
  96. debug("Your video will remain private until specified date.")
  97. tags = [u(s.strip()) for s in (options.tags or "").split(",")]
  98. ns = dict(title=title, n=index+1, total=total_videos)
  99. title_template = u(options.title_template)
  100. complete_title = (title_template.format(**ns) if total_videos > 1 else title)
  101. progress = get_progress_info()
  102. category_id = get_category_id(options.category)
  103. request_body = {
  104. "snippet": {
  105. "title": complete_title,
  106. "description": description,
  107. "categoryId": category_id,
  108. "tags": tags,
  109. "defaultLanguage": options.default_language,
  110. "defaultAudioLanguage": options.default_audio_language,
  111. },
  112. "status": {
  113. "privacyStatus": ("private" if options.publish_at else options.privacy),
  114. "publishAt": options.publish_at,
  115. },
  116. "recordingDetails": {
  117. "location": lib.string_to_dict(options.location),
  118. "recordingDate": options.recording_date,
  119. },
  120. }
  121. debug("Start upload: {0}".format(video_path))
  122. try:
  123. video_id = upload_video.upload(youtube, video_path,
  124. request_body, progress_callback=progress.callback,
  125. chunksize=options.chunksize)
  126. finally:
  127. progress.finish()
  128. return video_id
  129. def get_youtube_handler(options):
  130. """Return the API Youtube object."""
  131. home = os.path.expanduser("~")
  132. default_client_secrets = lib.get_first_existing_filename(
  133. [sys.prefix, os.path.join(sys.prefix, "local")],
  134. "share/youtube_upload/client_secrets.json")
  135. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  136. client_secrets = options.client_secrets or default_client_secrets or \
  137. os.path.join(home, ".client_secrets.json")
  138. credentials = options.credentials_file or default_credentials
  139. debug("Using client secrets: {0}".format(client_secrets))
  140. debug("Using credentials file: {0}".format(credentials))
  141. get_code_callback = (auth.browser.get_code
  142. if options.auth_browser else auth.console.get_code)
  143. return auth.get_resource(client_secrets, credentials,
  144. get_code_callback=get_code_callback)
  145. def parse_options_error(parser, options):
  146. """Check errors in options."""
  147. required_options = ["title"]
  148. missing = [opt for opt in required_options if not getattr(options, opt)]
  149. if missing:
  150. parser.print_usage()
  151. msg = "Some required option are missing: {0}".format(", ".join(missing))
  152. raise OptionsError(msg)
  153. def run_main(parser, options, args, output=sys.stdout):
  154. """Run the main scripts from the parsed options/args."""
  155. parse_options_error(parser, options)
  156. youtube = get_youtube_handler(options)
  157. if youtube:
  158. for index, video_path in enumerate(args):
  159. video_id = upload_youtube_video(youtube, options, video_path, len(args), index)
  160. video_url = WATCH_VIDEO_URL.format(id=video_id)
  161. debug("Video URL: {0}".format(video_url))
  162. if options.open_link:
  163. open_link(video_url) #Opens the Youtube Video's link in a webbrowser
  164. if options.thumb:
  165. youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
  166. if options.playlist:
  167. playlists.add_video_to_playlist(youtube, video_id,
  168. title=lib.to_utf8(options.playlist), privacy=options.privacy)
  169. output.write(video_id + "\n")
  170. else:
  171. raise AuthenticationError("Cannot get youtube resource")
  172. def main(arguments):
  173. """Upload videos to Youtube."""
  174. usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...]
  175. Upload videos to Youtube."""
  176. parser = optparse.OptionParser(usage)
  177. # Video metadata
  178. parser.add_option('-t', '--title', dest='title', type="string",
  179. help='Video title')
  180. parser.add_option('-c', '--category', dest='category', type="string",
  181. help='Video category')
  182. parser.add_option('-d', '--description', dest='description', type="string",
  183. help='Video description')
  184. parser.add_option('', '--description-file', dest='description_file', type="string",
  185. help='Video description file', default=None)
  186. parser.add_option('', '--tags', dest='tags', type="string",
  187. help='Video tags (separated by commas: "tag1, tag2,...")')
  188. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  189. default="public", help='Privacy status (public | unlisted | private)')
  190. parser.add_option('', '--publish-at', dest='publish_at', metavar="datetime",
  191. default=None, help='Publish date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ')
  192. parser.add_option('', '--location', dest='location', type="string",
  193. default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]",
  194. help='Video location"')
  195. parser.add_option('', '--recording-date', dest='recording_date', metavar="datetime",
  196. default=None, help="Recording date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ")
  197. parser.add_option('', '--default-language', dest='default_language', type="string",
  198. default=None, metavar="string",
  199. help="Default language (ISO 639-1: en | fr | de | ...)")
  200. parser.add_option('', '--default-audio-language', dest='default_audio_language', type="string",
  201. default=None, metavar="string",
  202. help="Default audio language (ISO 639-1: en | fr | de | ...)")
  203. parser.add_option('', '--thumbnail', dest='thumb', type="string", metavar="FILE",
  204. help='Image file to use as video thumbnail (JPEG or PNG)')
  205. parser.add_option('', '--playlist', dest='playlist', type="string",
  206. help='Playlist title (if it does not exist, it will be created)')
  207. parser.add_option('', '--title-template', dest='title_template',
  208. type="string", default="{title} [{n}/{total}]", metavar="string",
  209. help='Template for multiple videos (default: {title} [{n}/{total}])')
  210. # Authentication
  211. parser.add_option('', '--client-secrets', dest='client_secrets',
  212. type="string", help='Client secrets JSON file')
  213. parser.add_option('', '--credentials-file', dest='credentials_file',
  214. type="string", help='Credentials JSON file')
  215. parser.add_option('', '--auth-browser', dest='auth_browser', action='store_true',
  216. help='Open a GUI browser to authenticate if required')
  217. #Additional options
  218. parser.add_option('', '--chunksize', dest='chunksize', type="int",
  219. default = 1024*1024*8, help='Update file chunksize')
  220. parser.add_option('', '--open-link', dest='open_link', action='store_true',
  221. help='Opens a url in a web browser to display the uploaded video')
  222. options, args = parser.parse_args(arguments)
  223. if options.description_file is not None and os.path.exists(options.description_file):
  224. with open(options.description_file, encoding="utf-8") as file:
  225. options.description = file.read()
  226. try:
  227. run_main(parser, options, args)
  228. except googleapiclient.errors.HttpError as error:
  229. response = bytes.decode(error.content, encoding=lib.get_encoding()).strip()
  230. raise RequestError("Server response: {0}".format(response))
  231. def run():
  232. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))
  233. if __name__ == '__main__':
  234. run()