main.py 9.2 KB

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