main.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #!/usr/bin/python2
  2. #
  3. # Youtube-upload is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # Youtube-upload is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Youtube-upload. If not, see <http://www.gnu.org/licenses/>.
  15. #
  16. # Author: Arnau Sanchez <tokland@gmail.com>
  17. # Websites: http://code.google.com/p/youtube-upload
  18. # http://code.google.com/p/tokland
  19. """
  20. Upload a video to Youtube from the command-line.
  21. $ youtube-upload --title="A.S. Mutter playing" \
  22. --description="Anne Sophie Mutter plays Beethoven" \
  23. --category=Music \
  24. --keywords="mutter, beethoven" \
  25. anne_sophie_mutter.flv
  26. www.youtube.com/watch?v=pxzZ-fYjeYs
  27. """
  28. import os
  29. import sys
  30. import locale
  31. import optparse
  32. import collections
  33. import youtube_upload.auth
  34. import youtube_upload.upload_video
  35. import youtube_upload.categories
  36. # http://code.google.com/p/python-progressbar (>= 2.3)
  37. try:
  38. import progressbar
  39. except ImportError:
  40. progressbar = None
  41. class InvalidCategory(Exception): pass
  42. class VideoArgumentMissing(Exception): pass
  43. class OptionsMissing(Exception): pass
  44. class BadAuthentication(Exception): pass
  45. class ParseError(Exception): pass
  46. class VideoNotFound(Exception): pass
  47. class UnsuccessfulHTTPResponseCode(Exception): pass
  48. VERSION = "0.8.0"
  49. EXIT_CODES = {
  50. # Non-retryable
  51. BadAuthentication: 1,
  52. VideoArgumentMissing: 2,
  53. OptionsMissing: 2,
  54. InvalidCategory: 3,
  55. ParseError: 5,
  56. VideoNotFound: 6,
  57. # Retryable
  58. UnsuccessfulHTTPResponseCode: 100,
  59. }
  60. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  61. ProgressInfo = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  62. def to_utf8(s):
  63. """Re-encode string from the default system encoding to UTF-8."""
  64. current = locale.getpreferredencoding()
  65. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  66. def debug(obj, fd=sys.stderr):
  67. """Write obj to standard error."""
  68. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  69. if isinstance(obj, unicode) else obj)
  70. fd.write(string + "\n")
  71. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  72. """
  73. Catch exceptions on fun(*args, **kwargs) and return the exit code specified
  74. in the exit_codes dictionary. Return 0 if no exception is raised.
  75. """
  76. try:
  77. fun(*args, **kwargs)
  78. return 0
  79. except tuple(exit_codes.keys()) as exc:
  80. debug("[%s] %s" % (exc.__class__.__name__, exc))
  81. return exit_codes[exc.__class__]
  82. def get_encoding(fd):
  83. """Guess terminal encoding."""
  84. return fd.encoding or locale.getpreferredencoding()
  85. def compact(it):
  86. """Filter false (in the truth sense) elements in iterator."""
  87. return filter(bool, it)
  88. def tosize(seq, size):
  89. """Return list of fixed length from sequence."""
  90. return seq[:size] if len(seq) >= size else (seq + [None] * (size-len(seq)))
  91. def first(it):
  92. """Return first element in iterable."""
  93. return it.next()
  94. def get_progress_info():
  95. """Return a function callback to update the progressbar."""
  96. def _callback(total_size, completed):
  97. if not hasattr(bar, "next_update"):
  98. bar.maxval = total_size
  99. bar.start()
  100. bar.update(completed)
  101. widgets = [
  102. progressbar.Percentage(), ' ',
  103. progressbar.Bar(), ' ',
  104. progressbar.ETA(), ' ',
  105. progressbar.FileTransferSpeed(),
  106. ]
  107. bar = progressbar.ProgressBar(widgets=widgets)
  108. return ProgressInfo(callback=_callback, finish=bar.finish)
  109. def string_to_dict(string):
  110. """Return dictionary from string "key1=value1, key2=value2"."""
  111. pairs = [s.strip() for s in (string or "").split(",")]
  112. return dict(pair.split("=") for pair in pairs)
  113. def upload_video(youtube, options, video_path, total_videos, index):
  114. """Upload video with index (for split videos)."""
  115. title = to_utf8(options.title)
  116. description = to_utf8(options.description or "").decode("string-escape")
  117. ns = dict(title=title, n=index+1, total=total_videos)
  118. complete_title = \
  119. (options.title_template.format(**ns) if total_videos > 1 else title)
  120. progress = get_progress_info()
  121. if options.category:
  122. ids = youtube_upload.categories.IDS
  123. if options.category in ids:
  124. category_id = str(ids[options.category])
  125. else:
  126. msg = "{} is not a valid category".format(options.category)
  127. raise InvalidCategory(msg)
  128. else:
  129. category_id = None
  130. body = {
  131. "snippet": {
  132. "title": complete_title,
  133. "tags": map(str.strip, (options.keywords or "").split(",")),
  134. "description": description,
  135. "categoryId": category_id,
  136. },
  137. "status": {
  138. "privacyStatus": options.privacy
  139. },
  140. "recordingDetails": {
  141. "location": string_to_dict(options.location),
  142. },
  143. }
  144. video_id = youtube_upload.upload_video.upload(youtube, video_path, body,
  145. progress_callback=progress.callback, chunksize=16*1024)
  146. progress.finish()
  147. return video_id
  148. def run_main(parser, options, args, output=sys.stdout):
  149. """Run the main scripts from the parsed options/args."""
  150. required_options = ["title"]
  151. missing = [opt for opt in required_options if not getattr(options, opt)]
  152. if missing:
  153. parser.print_usage()
  154. msg = "Some required option are missing: %s" % ", ".join(missing)
  155. raise OptionsMissing(msg)
  156. default_client_secrets = \
  157. os.path.join(sys.prefix, "share/youtube_upload/client_secrets.json")
  158. home = os.path.expanduser("~")
  159. default_credentials = os.path.join(home, ".youtube_upload-credentials.json")
  160. client_secrets = options.client_secrets or default_client_secrets
  161. credentials = options.credentials_file or default_credentials
  162. debug("Using client secrets: {}".format(client_secrets))
  163. debug("Using credentials file: {}".format(credentials))
  164. youtube = youtube_upload.auth.get_resource(client_secrets, credentials)
  165. for index, video_path in enumerate(args):
  166. video_id = upload_video(youtube, options, video_path, len(args), index)
  167. video_url = WATCH_VIDEO_URL.format(id=video_id)
  168. debug("Watch URL: {}".format(video_url))
  169. output.write(video_id + "\n")
  170. def main(arguments):
  171. """Upload video to Youtube."""
  172. usage = """Usage: %prog [OPTIONS] VIDEO_PATH ...
  173. Upload videos to youtube."""
  174. parser = optparse.OptionParser(usage, version=VERSION)
  175. # Required options
  176. parser.add_option('-t', '--title', dest='title', type="string",
  177. help='Video(s) title')
  178. parser.add_option('-c', '--category', dest='category', type="string",
  179. help='Video(s) category')
  180. # Optional options
  181. parser.add_option('-d', '--description', dest='description', type="string",
  182. help='Video(s) description')
  183. parser.add_option('', '--keywords', dest='keywords', type="string",
  184. help='Video(s) keywords (separated by commas: tag1,tag2,...)')
  185. parser.add_option('', '--title-template', dest='title_template',
  186. type="string", default="$title [$n/$total]", metavar="STRING",
  187. help='Template for multiple videos (default: {title} [{n}/{total}])')
  188. parser.add_option('', '--privacy', dest='privacy', metavar="STRING",
  189. default="public", help='Privacy status (public | unlisted | private)')
  190. parser.add_option('', '--location', dest='location', type="string",
  191. default=None, metavar="LAT,LON",
  192. help='Video(s) location (latitude=VAL, longitude=VAL, altitude=VAL)."')
  193. # Authentication
  194. parser.add_option('', '--client-secrets', dest='client_secrets',
  195. type="string", help='Client secrets JSON file')
  196. parser.add_option('', '--credentials-file', dest='credentials_file',
  197. type="string", help='Client secrets JSON file')
  198. options, args = parser.parse_args(arguments)
  199. run_main(parser, options, args)
  200. if __name__ == '__main__':
  201. sys.exit(catch_exceptions(EXIT_CODES, main, sys.argv[1:]))