main.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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.ETA(), ' ',
  59. progressbar.FileTransferSpeed(),
  60. ])
  61. def _callback(total_size, completed):
  62. if not hasattr(bar, "next_update"):
  63. if hasattr(bar, "maxval"):
  64. bar.maxval = total_size
  65. else:
  66. bar.max_value = total_size
  67. bar.start()
  68. bar.update(completed)
  69. def _finish():
  70. if hasattr(bar, "next_update"):
  71. return bar.finish()
  72. return progressinfo(callback=_callback, finish=_finish)
  73. else:
  74. return progressinfo(callback=None, finish=lambda: True)
  75. def get_category_id(category):
  76. """Return category ID from its name."""
  77. if category:
  78. if category in categories.IDS:
  79. ncategory = categories.IDS[category]
  80. debug("Using category: {0} (id={1})".format(category, ncategory))
  81. return str(categories.IDS[category])
  82. else:
  83. msg = "{0} is not a valid category".format(category)
  84. raise InvalidCategory(msg)
  85. def upload_youtube_video(youtube, options, video_path, total_videos, index):
  86. """Upload video with index (for split videos)."""
  87. u = lib.to_utf8
  88. title = u(options.title)
  89. if hasattr(u('string'), 'decode'):
  90. description = u(options.description or "").decode("string-escape")
  91. else:
  92. description = options.description
  93. if options.publish_at:
  94. debug("Your video will remain private until specified date.")
  95. tags = [u(s.strip()) for s in (options.tags or "").split(",")]
  96. ns = dict(title=title, n=index+1, total=total_videos)
  97. title_template = u(options.title_template)
  98. complete_title = (title_template.format(**ns) if total_videos > 1 else title)
  99. progress = get_progress_info()
  100. category_id = get_category_id(options.category)
  101. request_body = {
  102. "snippet": {
  103. "title": complete_title,
  104. "description": description,
  105. "categoryId": category_id,
  106. "tags": tags,
  107. "defaultLanguage": options.default_language,
  108. "defaultAudioLanguage": options.default_audio_language,
  109. },
  110. "status": {
  111. "privacyStatus": ("private" if options.publish_at else options.privacy),
  112. "publishAt": options.publish_at,
  113. },
  114. "recordingDetails": {
  115. "location": lib.string_to_dict(options.location),
  116. "recordingDate": options.recording_date,
  117. },
  118. }
  119. debug("Start upload: {0}".format(video_path))
  120. try:
  121. video_id = upload_video.upload(youtube, video_path,
  122. request_body, progress_callback=progress.callback)
  123. finally:
  124. progress.finish()
  125. return video_id
  126. def get_youtube_handler(options):
  127. """Return the API Youtube object."""
  128. home = os.path.expanduser("~")
  129. default_client_secrets = lib.get_first_existing_filename(
  130. [sys.prefix, os.path.join(sys.prefix, "local")],
  131. "share/youtube_upload/client_secrets.json")
  132. default_credentials = os.path.join(home, ".youtube-upload-credentials.json")
  133. client_secrets = options.client_secrets or default_client_secrets or \
  134. os.path.join(home, ".client_secrets.json")
  135. credentials = options.credentials_file or default_credentials
  136. debug("Using client secrets: {0}".format(client_secrets))
  137. debug("Using credentials file: {0}".format(credentials))
  138. get_code_callback = (auth.browser.get_code
  139. if options.auth_browser else auth.console.get_code)
  140. return auth.get_resource(client_secrets, credentials,
  141. get_code_callback=get_code_callback)
  142. def parse_options_error(parser, options):
  143. """Check errors in options."""
  144. required_options = ["title"]
  145. missing = [opt for opt in required_options if not getattr(options, opt)]
  146. if missing:
  147. parser.print_usage()
  148. msg = "Some required option are missing: {0}".format(", ".join(missing))
  149. raise OptionsError(msg)
  150. def run_main(parser, options, args, output=sys.stdout):
  151. """Run the main scripts from the parsed options/args."""
  152. parse_options_error(parser, options)
  153. youtube = get_youtube_handler(options)
  154. if youtube:
  155. for index, video_path in enumerate(args):
  156. video_id = upload_youtube_video(youtube, options, video_path, len(args), index)
  157. video_url = WATCH_VIDEO_URL.format(id=video_id)
  158. debug("Video URL: {0}".format(video_url))
  159. if options.open_link:
  160. open_link(video_url) #Opens the Youtube Video's link in a webbrowser
  161. if options.thumb:
  162. youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
  163. if options.playlist:
  164. playlists.add_video_to_playlist(youtube, video_id,
  165. title=lib.to_utf8(options.playlist), privacy=options.privacy)
  166. output.write(video_id + "\n")
  167. else:
  168. raise AuthenticationError("Cannot get youtube resource")
  169. def main(arguments):
  170. """Upload videos to Youtube."""
  171. usage = """Usage: %prog [OPTIONS] VIDEO [VIDEO2 ...]
  172. Upload videos to Youtube."""
  173. parser = optparse.OptionParser(usage)
  174. # Video metadata
  175. parser.add_option('-t', '--title', dest='title', type="string",
  176. help='Video title')
  177. parser.add_option('-c', '--category', dest='category', type="string",
  178. help='Video category')
  179. parser.add_option('-d', '--description', dest='description', type="string",
  180. help='Video description')
  181. parser.add_option('', '--tags', dest='tags', type="string",
  182. help='Video tags (separated by commas: "tag1, tag2,...")')
  183. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  184. default="public", help='Privacy status (public | unlisted | private)')
  185. parser.add_option('', '--publish-at', dest='publish_at', metavar="datetime",
  186. default=None, help='Publish date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ')
  187. parser.add_option('', '--location', dest='location', type="string",
  188. default=None, metavar="latitude=VAL,longitude=VAL[,altitude=VAL]",
  189. help='Video location"')
  190. parser.add_option('', '--recording-date', dest='recording_date', metavar="datetime",
  191. default=None, help="Recording date (ISO 8601): YYYY-MM-DDThh:mm:ss.sZ")
  192. parser.add_option('', '--default-language', dest='default_language', type="string",
  193. default=None, metavar="string",
  194. help="Default language (ISO 639-1: en | fr | de | ...)")
  195. parser.add_option('', '--default-audio-language', dest='default_audio_language', type="string",
  196. default=None, metavar="string",
  197. help="Default audio language (ISO 639-1: en | fr | de | ...)")
  198. parser.add_option('', '--thumbnail', dest='thumb', type="string",
  199. help='Video thumbnail')
  200. parser.add_option('', '--playlist', dest='playlist', type="string",
  201. help='Playlist title (if it does not exist, it will be created)')
  202. parser.add_option('', '--title-template', dest='title_template',
  203. type="string", default="{title} [{n}/{total}]", metavar="string",
  204. help='Template for multiple videos (default: {title} [{n}/{total}])')
  205. # Authentication
  206. parser.add_option('', '--client-secrets', dest='client_secrets',
  207. type="string", help='Client secrets JSON file')
  208. parser.add_option('', '--credentials-file', dest='credentials_file',
  209. type="string", help='Credentials JSON file')
  210. parser.add_option('', '--auth-browser', dest='auth_browser', action='store_true',
  211. help='Open a GUI browser to authenticate if required')
  212. #Additional options
  213. parser.add_option('', '--open-link', dest='open_link', action='store_true',
  214. help='Opens a url in a web browser to display the uploaded video')
  215. options, args = parser.parse_args(arguments)
  216. try:
  217. run_main(parser, options, args)
  218. except googleapiclient.errors.HttpError as error:
  219. raise RequestError("Server response: {0}".format(bytes.decode(error.content).strip()))
  220. def run():
  221. sys.exit(lib.catch_exceptions(EXIT_CODES, main, sys.argv[1:]))
  222. if __name__ == '__main__':
  223. run()