home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / BitTorrent / ConvertedMetainfo.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  9.2 KB  |  238 lines

  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.0 (the License).  You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License.  You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10.  
  11. # Written by Uoti Urpala
  12.  
  13. # required for Python 2.2
  14. from __future__ import generators
  15.  
  16. import os
  17. import sys
  18. from sha import sha
  19.  
  20. from BitTorrent.obsoletepythonsupport import *
  21.  
  22. from BitTorrent.bencode import bencode
  23. from BitTorrent import btformats
  24. from BitTorrent import WARNING, ERROR
  25.  
  26.  
  27. WINDOWS_UNSUPPORTED_CHARS ='"*/:<>?\|'
  28. windows_translate = [chr(i) for i in range(256)]
  29. for x in WINDOWS_UNSUPPORTED_CHARS:
  30.     windows_translate[ord(x)] = '-'
  31. windows_translate = ''.join(windows_translate)
  32.  
  33. noncharacter_translate = {}
  34. for i in range(0xD800, 0xE000):
  35.     noncharacter_translate[i] = ord('-')
  36. for i in range(0xFDD0, 0xFDF0):
  37.     noncharacter_translate[i] = ord('-')
  38. for i in (0xFFFE, 0xFFFF):
  39.     noncharacter_translate[i] = ord('-')
  40.  
  41. del x, i
  42.  
  43. def set_filesystem_encoding(encoding, errorfunc):
  44.     global filesystem_encoding
  45.     filesystem_encoding = 'ascii'
  46.     if encoding == '':
  47.         try:
  48.             sys.getfilesystemencoding
  49.         except AttributeError:
  50.             errorfunc(WARNING, "This seems to be an old Python version which does not support detecting the filesystem encoding. Assuming 'ascii'.")
  51.             return
  52.         encoding = sys.getfilesystemencoding()
  53.         if encoding is None:
  54.             errorfunc(WARNING, "Python failed to autodetect filesystem encoding. Using 'ascii' instead.")
  55.             return
  56.     try:
  57.         'a1'.decode(encoding)
  58.     except:
  59.         errorfunc(ERROR, "Filesystem encoding '"+encoding+"' is not supported. Using 'ascii' instead.")
  60.         return
  61.     filesystem_encoding = encoding
  62.  
  63.  
  64. def generate_names(name, is_dir):
  65.     if is_dir:
  66.         prefix = name + '.'
  67.         suffix = ''
  68.     else:
  69.         pos = name.rfind('.')
  70.         if pos == -1:
  71.             pos = len(name)
  72.         prefix = name[:pos] + '.'
  73.         suffix = name[pos:]
  74.     i = 0
  75.     while True:
  76.         yield prefix + str(i) + suffix
  77.         i += 1
  78.  
  79.  
  80. class ConvertedMetainfo(object):
  81.  
  82.     def __init__(self, metainfo):
  83.         self.bad_torrent_wrongfield = False
  84.         self.bad_torrent_unsolvable = False
  85.         self.bad_torrent_noncharacter = False
  86.         self.bad_conversion = False
  87.         self.bad_windows = False
  88.         self.bad_path = False
  89.         self.reported_errors = False
  90.         self.is_batch = False
  91.         self.orig_files = None
  92.         self.files_fs = None
  93.         self.total_bytes = 0
  94.         self.sizes = []
  95.  
  96.         btformats.check_message(metainfo, check_paths=False)
  97.         info = metainfo['info']
  98.         if info.has_key('length'):
  99.             self.total_bytes = info['length']
  100.             self.sizes.append(self.total_bytes)
  101.         else:
  102.             self.is_batch = True
  103.             r = []
  104.             self.orig_files = []
  105.             self.sizes = []
  106.             i = 0
  107.             for f in info['files']:
  108.                 l = f['length']
  109.                 self.total_bytes += l
  110.                 self.sizes.append(l)
  111.                 path = self._get_attr_utf8(f, 'path')
  112.                 for x in path:
  113.                     if not btformats.allowed_path_re.match(x):
  114.                         if l > 0:
  115.                             raise BTFailure("Bad file path component: "+x)
  116.                         # BitComet makes bad .torrent files with empty
  117.                         # filename part
  118.                         self.bad_path = True
  119.                         break
  120.                 else:
  121.                     path = [(self._enforce_utf8(x), x) for x in path]
  122.                     self.orig_files.append('/'.join([x[0] for x in path]))
  123.                     r.append(([(self._to_fs_2(u), u, o) for u, o in path], i))
  124.                     i += 1
  125.             # If two or more file/subdirectory names in the same directory
  126.             # would map to the same name after encoding conversions + Windows
  127.             # workarounds, change them. Files are changed as
  128.             # 'a.b.c'->'a.b.0.c', 'a.b.1.c' etc, directories or files without
  129.             # '.' as 'a'->'a.0', 'a.1' etc. If one of the multiple original
  130.             # names was a "clean" conversion, that one is always unchanged
  131.             # and the rest are adjusted.
  132.             r.sort()
  133.             self.files_fs = [None] * len(r)
  134.             prev = [None]
  135.             res = []
  136.             stack = [{}]
  137.             for x in r:
  138.                 j = 0
  139.                 x, i = x
  140.                 while x[j] == prev[j]:
  141.                     j += 1
  142.                 del res[j:]
  143.                 del stack[j+1:]
  144.                 name = x[j][0][1]
  145.                 if name in stack[-1]:
  146.                     for name in generate_names(x[j][1], j != len(x) - 1):
  147.                         name = self._to_fs(name)
  148.                         if name not in stack[-1]:
  149.                             break
  150.                 stack[-1][name] = None
  151.                 res.append(name)
  152.                 for j in range(j + 1, len(x)):
  153.                     name = x[j][0][1]
  154.                     stack.append({name: None})
  155.                     res.append(name)
  156.                 self.files_fs[i] = os.path.join(*res)
  157.                 prev = x
  158.  
  159.         self.name = self._get_field_utf8(info, 'name')
  160.         self.name_fs = self._to_fs(self.name)
  161.         self.piece_length = info['piece length']
  162.         self.announce = metainfo['announce']
  163.         self.hashes = [info['pieces'][x:x+20] for x in xrange(0,
  164.             len(info['pieces']), 20)]
  165.         self.infohash = sha(bencode(info)).digest()
  166.  
  167.     def show_encoding_errors(self, errorfunc):
  168.         self.reported_errors = True
  169.         if self.bad_torrent_unsolvable:
  170.             errorfunc(ERROR, "This .torrent file has been created with a broken tool and has incorrectly encoded filenames. Some or all of the filenames may appear different from what the creator of the .torrent file intended.")
  171.         elif self.bad_torrent_noncharacter:
  172.             errorfunc(ERROR, "This .torrent file has been created with a broken tool and has bad character values that do not correspond to any real character. Some or all of the filenames may appear different from what the creator of the .torrent file intended.")
  173.         elif self.bad_torrent_wrongfield:
  174.             errorfunc(ERROR, "This .torrent file has been created with a broken tool and has incorrectly encoded filenames. The names used may still be correct.")
  175.         elif self.bad_conversion:
  176.             errorfunc(WARNING, 'The character set used on the local filesystem ("'+filesystem_encoding+'") cannot represent all characters used in the filename(s) of this torrent. Filenames have been changed from the original.')
  177.         elif self.bad_windows:
  178.             errorfunc(WARNING, 'The Windows filesystem cannot handle some characters used in the filename(s) of this torrent. Filenames have been changed from the original.')
  179.         elif self.bad_path:
  180.             errorfunc(WARNING, "This .torrent file has been created with a broken tool and has at least 1 file with an invalid file or directory name. However since all such files were marked as having length 0 those files are just ignored.")
  181.  
  182.     # At least BitComet seems to make bad .torrent files that have
  183.     # fields in an arbitrary encoding but separate 'field.utf-8' attributes
  184.     def _get_attr_utf8(self, d, attrib):
  185.         v = d.get(attrib + '.utf-8')
  186.         if v is not None:
  187.             if v != d[attrib]:
  188.                 self.bad_torrent_wrongfield = True
  189.         else:
  190.             v = d[attrib]
  191.         return v
  192.  
  193.     def _enforce_utf8(self, s):
  194.         try:
  195.             s = s.decode('utf-8')
  196.         except:
  197.             self.bad_torrent_unsolvable = True
  198.             s = s.decode('utf-8', 'replace')
  199.         t = s.translate(noncharacter_translate)
  200.         if t != s:
  201.             self.bad_torrent_noncharacter = True
  202.         return t.encode('utf-8')
  203.  
  204.     def _get_field_utf8(self, d, attrib):
  205.         r = self._get_attr_utf8(d, attrib)
  206.         return self._enforce_utf8(r)
  207.  
  208.     def _fix_windows(self, name, t=windows_translate):
  209.         bad = False
  210.         r = name.translate(t)
  211.         # for some reason name cannot end with '.' or space
  212.         if r[-1] in '. ':
  213.             r = r + '-'
  214.         if r != name:
  215.             self.bad_windows = True
  216.             bad = True
  217.         return (r, bad)
  218.  
  219.     def _to_fs(self, name):
  220.         return self._to_fs_2(name)[1]
  221.  
  222.     def _to_fs_2(self, name):
  223.         bad = False
  224.         if sys.platform == 'win32':
  225.             name, bad = self._fix_windows(name)
  226.         name = name.decode('utf-8')
  227.         try:
  228.             r = name.encode(filesystem_encoding)
  229.         except:
  230.             self.bad_conversion = True
  231.             bad = True
  232.             r = name.encode(filesystem_encoding, 'replace')
  233.             # 'replace' could possibly make the name unsupported by windows
  234.             # again, but I think this shouldn't happen with the 'mbcs'
  235.             # encoding. Could happen under Python 2.2 or if someone explicitly
  236.             # specifies a stupid encoding...
  237.         return (bad, r)
  238.