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 <pyarnau@gmail.com>
  17. # Site: https://github.com/tokland/youtube-upload
  18. """
  19. Upload a video to Youtube from the command-line.
  20. $ youtube-upload --title="A.S. Mutter playing" \
  21. --description="Anne Sophie Mutter plays Beethoven" \
  22. --category=Music \
  23. --keywords="mutter, beethoven" \
  24. anne_sophie_mutter.flv
  25. www.youtube.com/watch?v=pxzZ-fYjeYs
  26. """
  27. import os
  28. import sys
  29. import locale
  30. import optparse
  31. import collections
  32. import youtube_upload.auth
  33. import youtube_upload.upload_video
  34. import youtube_upload.categories
  35. # http://code.google.com/p/python-progressbar (>= 2.3)
  36. try:
  37. import progressbar
  38. except ImportError:
  39. progressbar = None
  40. class InvalidCategory(Exception): pass
  41. class VideoArgumentMissing(Exception): pass
  42. class OptionsMissing(Exception): pass
  43. class BadAuthentication(Exception): pass
  44. class ParseError(Exception): pass
  45. class VideoNotFound(Exception): pass
  46. class UnsuccessfulHTTPResponseCode(Exception): pass
  47. VERSION = "0.8.0"
  48. EXIT_CODES = {
  49. # Non-retryable
  50. BadAuthentication: 1,
  51. VideoArgumentMissing: 2,
  52. OptionsMissing: 2,
  53. InvalidCategory: 3,
  54. ParseError: 5,
  55. VideoNotFound: 6,
  56. # Retryable
  57. UnsuccessfulHTTPResponseCode: 100,
  58. }
  59. WATCH_VIDEO_URL = "https://www.youtube.com/watch?v={id}"
  60. ProgressInfo = collections.namedtuple("ProgressInfo", ["callback", "finish"])
  61. def to_utf8(s):
  62. """Re-encode string from the default system encoding to UTF-8."""
  63. current = locale.getpreferredencoding()
  64. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  65. def debug(obj, fd=sys.stderr):
  66. """Write obj to standard error."""
  67. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  68. if isinstance(obj, unicode) else obj)
  69. fd.write(string + "\n")
  70. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  71. """
  72. Catch exceptions on fun(*args, **kwargs) and return the exit code specified
  73. in the exit_codes dictionary. Return 0 if no exception is raised.
  74. """
  75. try:
  76. fun(*args, **kwargs)
  77. return 0
  78. except tuple(exit_codes.keys()) as exc:
  79. debug("[%s] %s" % (exc.__class__.__name__, exc))
  80. return exit_codes[exc.__class__]
  81. def get_encoding(fd):
  82. """Guess terminal encoding."""
  83. return fd.encoding or locale.getpreferredencoding()
  84. def compact(it):
  85. """Filter false (in the truth sense) elements in iterator."""
  86. return filter(bool, it)
  87. def tosize(seq, size):
  88. """Return list of fixed length from sequence."""
  89. return seq[:size] if len(seq) >= size else (seq + [None] * (size-len(seq)))
  90. def first(it):
  91. """Return first element in iterable."""
  92. return it.next()
  93. def get_progress_info():
  94. """Return a function callback to update the progressbar."""
  95. def _callback(total_size, completed):
  96. if not hasattr(bar, "next_update"):
  97. bar.maxval = total_size
  98. bar.start()
  99. bar.update(completed)
  100. widgets = [
  101. progressbar.Percentage(), ' ',
  102. progressbar.Bar(), ' ',
  103. progressbar.ETA(), ' ',
  104. progressbar.FileTransferSpeed(),
  105. ]
  106. bar = progressbar.ProgressBar(widgets=widgets)
  107. return ProgressInfo(callback=_callback, finish=bar.finish)
  108. def string_to_dict(string):
  109. """Return dictionary from string "key1=value1, key2=value2"."""
  110. pairs = [s.strip() for s in (string or "").split(",")]
  111. return dict(pair.split("=") for pair in pairs)
  112. def upload_video(youtube, options, video_path, total_videos, index):
  113. """Upload video with index (for split videos)."""
  114. title = to_utf8(options.title)
  115. description = to_utf8(options.description or "").decode("string-escape")
  116. ns = dict(title=title, n=index+1, total=total_videos)
  117. complete_title = \
  118. (options.title_template.format(**ns) if total_videos > 1 else title)
  119. progress = get_progress_info()
  120. if options.category:
  121. ids = youtube_upload.categories.IDS
  122. if options.category in ids:
  123. category_id = str(ids[options.category])
  124. else:
  125. msg = "{} is not a valid category".format(options.category)
  126. raise InvalidCategory(msg)
  127. else:
  128. category_id = None
  129. body = {
  130. "snippet": {
  131. "title": complete_title,
  132. "tags": map(str.strip, (options.keywords or "").split(",")),
  133. "description": description,
  134. "categoryId": category_id,
  135. },
  136. "status": {
  137. "privacyStatus": options.privacy
  138. },
  139. "recordingDetails": {
  140. "location": string_to_dict(options.location),
  141. },
  142. }
  143. debug("Start upload: {} ({})".format(video_path, complete_title))
  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 [VIDEO_PATH2 ...]
  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="latitude=VAL, longitude=VAL, altitude=VAL",
  192. help='Video(s) location"')
  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:]))