def saveData(self, fileName, data, shouldUnzip=True):
        log(__name__ ,"Saving to %s (size %d)" % (fileName, len(data)))
        # Save the downloaded zip file
        with open( fileName,"wb") as f:
            f.write(data)
        
        if shouldUnzip:
            # Unzip the zip file
            log(__name__ ,"Unzip the zip file")
            zipDirPath = os.path.dirname(fileName)
            zip = zipfile.ZipFile(fileName, "r")
            zip.extractall(zipDirPath)
            zip.close()
            # Remove the unneeded zip file
            os.remove(fileName)
            
            for srtFile in os.listdir(zipDirPath):
	        if srtFile.endswith(".srt"):
                    srtFile = os.path.join(zipDirPath,srtFile)
                    
                    #convert file from cp1255 to utf-8
                    tempFileName=srtFile+ ".tmp"
                    convert_file(srtFile,tempFileName)
                    shutil.copy(tempFileName,srtFile)
                    os.remove(tempFileName)
Beispiel #2
0
    def login(self):
        username = self.__addon__.getSetting("username")
        password = self.__addon__.getSetting("password")
        log(__name__,
            "Checking if the user filled login credentials on Settings")
        if not username or not password:
            log(__name__, "No login creds, failing back to guest")
            return False

        log(__name__,
            "Settings filled with username and password, trying to login")
        login_data_ = {
            "form": "true",
            "username": username,
            "password": password,
        }
        login_data = urllib.urlencode(login_data_)
        rnd_float = random.uniform(0.1, 0.9)
        login_url = 'http://www.torec.net/ajax/login/t7/loginProcess.asp?rnd={0}'.format(
            rnd_float)
        log(__name__, "Login URL: %s" % login_url)
        # For debug, not for prod - will pring credentials to log.
        #log(__name__, "Login params: %s" % login_data)
        response = self.opener.open(login_url, login_data)
        content = ''.join(response.read())
        log(__name__, "Response: %s" % content)
        self.cj.save(ignore_discard=True)
        return username in content
    def login(self):
        username = self.__addon__.getSetting("username")
        password = self.__addon__.getSetting("password")
        log(__name__, "Checking if the user filled login credentials on Settings")
        if not username or not password:
            log(__name__, "No login creds, failing back to guest")
            return False

        log(__name__, "Settings filled with username and password, trying to login")
        login_data_ = {
            "form": "true",
            "username": username,
            "password": password,
        }
        login_data = urllib.urlencode(login_data_)
        rnd_float = random.uniform(0.1, 0.9)
        login_url = 'http://www.torec.net/ajax/login/t7/loginProcess.asp?rnd={0}'.format(rnd_float)
        log(__name__, "Login URL: %s" % login_url)
        # For debug, not for prod - will pring credentials to log.
        #log(__name__, "Login params: %s" % login_data)
        response = self.opener.open(login_url, login_data)
        content = ''.join(response.read())
        log(__name__, "Response: %s" % content)
        self.cj.save(ignore_discard=True)
        return username in content
Beispiel #4
0
    def search_movie(self, movie_name):
        main_url = self._fetch_main_url(movie_name)
        if not main_url:
            log(__name__, "couldn't find main URL for %s" % movie_name)
            return None

        return self._fetch_subtitles_options(main_url)
    def saveData(self, fileName, data, shouldUnzip=True):
        log(__name__, "Saving to %s (size %d)" % (fileName, len(data)))
        # Save the downloaded zip file
        with open(fileName, "wb") as f:
            f.write(data)

        if shouldUnzip:
            # Unzip the zip file
            log(__name__, "Unzip the zip file")
            zipDirPath = os.path.dirname(fileName)
            zip = zipfile.ZipFile(fileName, "r")
            zip.extractall(zipDirPath)
            zip.close()
            # Remove the unneeded zip file
            os.remove(fileName)

            for srtFile in os.listdir(zipDirPath):
                if srtFile.endswith(".srt"):
                    srtFile = os.path.join(zipDirPath, srtFile)

                    #convert file from cp1255 to utf-8
                    tempFileName = srtFile + ".tmp"
                    convert_file(srtFile, tempFileName)
                    shutil.copy(tempFileName, srtFile)
                    os.remove(tempFileName)
    def search_movie(self, movie_name):
        main_url = self._fetch_main_url(movie_name)
        if not main_url:
            log(__name__, "couldn't find main URL for %s" % movie_name)
            return None

        return self._fetch_subtitles_options(main_url)
Beispiel #7
0
    def download(self, download_link):
        if not download_link:
            log(__name__, "no download link found")
            return None, None

        response = self.opener.open("%s%s" % (self.BASE_URL, download_link))
        data = response.read()
        file_name = re.search(
            "filename=(.*)",
            response.headers["content-disposition"]).groups()[0]
        return data, file_name
    def search_tvshow(self, tvshow_name, season_number, episode_number):
        main_url = self._fetch_main_url(tvshow_name)
        if not main_url:
            log(__name__, "couldn't find main URL for %s" % tvshow_name)
            return None

        episode_url = self._fetch_episode_url(main_url, season_number, episode_number)
        if not episode_url:
            log(__name__, "couldn't find episode URL for tvshow name %s, season %s episode %s" % (tvshow_name, season_number, episode_number))
            return None            
        
        return self._fetch_subtitles_options(episode_url)
Beispiel #9
0
def convert_to_utf(file):
  ''' 
  Convert a file in cp1255 encoding to utf-8
  :param file: file to converted from CP1255 to UTF8
  '''
  try:
    with codecs.open(file,"r","cp1255") as f:
      srtData = f.read()

    with codecs.open(file, 'w', 'utf-8') as output:
      output.write(srtData)
  except UnicodeDecodeError:
    log(__name__, "got unicode decode error with reading subtitle data")
    def download(self, download_link):
        if not download_link:
            log(__name__, "no download link found")
            return None, None

        response = self.opener.open(
            "%s%s" % (self.BASE_URL, download_link)
        )
        data = response.read()
        file_name = re.search(
            "filename=(.*)", response.headers["content-disposition"]
        ).groups()[0]
        return data, file_name
Beispiel #11
0
    def _get_download_link_with_login(self, sub_id, option_id):
        # Checking if we have cookie - if so, we will try to use it
        log(__name__, "Checking if we have cookie")
        cookie_root = 'www.torec.net'
        cookie_name = 'Torec%5FNC%5Fsite'
        if cookie_root in self.cj._cookies and \
           cookie_name in self.cj._cookies[cookie_root]['/'] and \
           self.__addon__.getSetting("username") in self.cj._cookies[cookie_root]['/'][cookie_name].value:
            log(__name__, "Cookie found. Trying to get link")
            download_link = self._try_get_download_link(
                sub_id, option_id, None, True)
            if download_link:
                return download_link

        # Checking if the user has credentials, if so - logging in and downloading,
        # If not (or the login failed) - failing back to guest user download
        log(__name__, "Trying to login")
        if self.login():
            log(__name__, "Logged in. Trying to get link")
            download_link = self._try_get_download_link(
                sub_id, option_id, None, True)
            if download_link:
                return download_link

        return None
Beispiel #12
0
    def _fetch_main_url(self, name):
        log(__name__, "fetching main url for name %s" % name)
        search_response = self.opener.open(
            "%s/ajax/search/acSearch.asp" % self.BASE_URL,
            urllib.urlencode({"query": name}))

        suggestions = search_response.read()
        if not suggestions:
            log(__name__, "couldn't find suggestions for query %s" % name)
            return None

        try:
            json_suggestions = json.loads(suggestions)
            return json_suggestions["suggestions"][0]["data"]
        except ValueError, e:
            return None
Beispiel #13
0
    def search_tvshow(self, tvshow_name, season_number, episode_number):
        main_url = self._fetch_main_url(tvshow_name)
        if not main_url:
            log(__name__, "couldn't find main URL for %s" % tvshow_name)
            return None

        episode_url = self._fetch_episode_url(main_url, season_number,
                                              episode_number)
        if not episode_url:
            log(
                __name__,
                "couldn't find episode URL for tvshow name %s, season %s episode %s"
                % (tvshow_name, season_number, episode_number))
            return None

        return self._fetch_subtitles_options(episode_url)
    def _fetch_main_url(self, name):
        log(__name__, "fetching main url for name %s" % name)
        search_response = self.opener.open(
            "%s/ajax/search/acSearch.asp" % self.BASE_URL,
            urllib.urlencode({"query": name }))

        suggestions = search_response.read()
        if not suggestions:
            log(__name__, "couldn't find suggestions for query %s" % name)
            return None

        try:
            json_suggestions = json.loads(suggestions)
            return json_suggestions["suggestions"][0]["data"]
        except ValueError, e:
            return None
Beispiel #15
0
def search(item):
    best_match_id = None
    downloader = TorecSubtitlesDownloader()

    try:
        search_string = build_search_string(item)
        search_data = downloader.getSubtitleMetaData(search_string)

        log(__name__, "search_data=%s" % str(search_data))
        if search_data != None:
            best_match_id = downloader.getBestMatchID(
                os.path.basename(item['file_original_path']), search_data)
    except:
        log(__name__, "failed to connect to service for subtitle search")
        xbmc.executebuiltin(
            (u'Notification(%s,%s)' %
             (__scriptname__, __language__(32001))).encode('utf-8'))
        return

    list_items = []
    if search_data != None:
        for item_data in search_data.options:
            listitem = xbmcgui.ListItem(
                label="Hebrew",
                label2=item_data.name,
                iconImage="0",
                thumbnailImage="he",
            )

            url = "plugin://%s/?action=download&page_id=%s&subtitle_id=%s&filename=%s" % (
                __scriptid__, search_data.id, item_data.id, item_data.name)

            if best_match_id != None and item_data.id == best_match_id:
                listitem.setProperty("sync", "true")
                list_items.insert(0, (
                    url,
                    listitem,
                    False,
                ))
            else:
                list_items.append((
                    url,
                    listitem,
                    False,
                ))

    xbmcplugin.addDirectoryItems(handle=int(sys.argv[1]), items=list_items)
    def _get_download_link_with_regular_token(self, sub_id, option_id):
        guest_token = self._request_subtitle(sub_id)

        download_link  = None
        waited_msec    = 0.0

        # Torec website may delay download up to 13 seconds
        while (not xbmc.abortRequested) and (waited_msec < self.MAXIMUM_WAIT_TIME_MSEC):
            download_link = self._try_get_download_link(sub_id, option_id, guest_token) 
            if download_link:
                break

            xbmc.sleep(500)
            waited_msec += 500
        
        log(__name__, "received link after sleeping %f seconds" % (waited_msec / 1000.0))

        return download_link
def download(page_id, subtitle_id,filename, stack=False):
    subtitle_list = []
    exts          = [".srt", ".sub"]
    
    delay         = 20
    download_wait = delay
    downloader    = TorecSubtitlesDownloader()
    start_time    = time.time()

    delete_old_subs()
    try:
        # Wait the minimal time needed for retrieving the download link
        for i in range (int(download_wait)):
            result =  downloader.getDownloadLink(page_id, subtitle_id, False)
            if (result != None):
                break
            log(__name__ ,"download will start in %i seconds" % (delay,))
            delay -= 1
            time.sleep(1)
    except:
        log( __name__, "failed to connect to service for subtitle download")
        return subtitle_list
        
    if result != None:
        log(__name__ ,"Downloading subtitles from '%s'" % result)
        
        (subtitleData, subtitleName) = downloader.download(result)
        (fileName, fileExt) = os.path.splitext(subtitleName)
        archiveFile = os.path.join(__temp__, "Torec%s" % fileExt)
        with open(archiveFile, "wb") as subFile:
            subFile.write(subtitleData)

        xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (archiveFile,__temp__,)).encode('utf-8'), True)

        for file in xbmcvfs.listdir(__temp__)[1]:
            ufile=file.decode('utf-8')
            log(__name__, "file=%s" % ufile)
            file = os.path.join(__temp__, ufile)
            if (os.path.splitext(ufile)[1] in exts):
              convert_to_utf(file)
              subtitle_list.append(file)
      
    log(__name__, "Overall download took %f" % (time.time() - start_time))
    return subtitle_list
Beispiel #18
0
    def _get_download_link_with_regular_token(self, sub_id, option_id):
        guest_token = self._request_subtitle(sub_id)

        download_link = None
        waited_msec = 0.0

        # Torec website may delay download up to 13 seconds
        while (not xbmc.abortRequested) and (waited_msec <
                                             self.MAXIMUM_WAIT_TIME_MSEC):
            download_link = self._try_get_download_link(
                sub_id, option_id, guest_token)
            if download_link:
                break

            xbmc.sleep(500)
            waited_msec += 500

        log(__name__,
            "received link after sleeping %f seconds" % (waited_msec / 1000.0))

        return download_link
 def saveData(self, fileName, data, shouldUnzip=True):
     log(__name__ ,"Saving to %s (size %d)" % (fileName, len(data)))
     # Save the downloaded zip file
     with open( fileName,"wb") as f:
         f.write(data)
     
     if shouldUnzip:
         # Unzip the zip file
         log(__name__ ,"Unzip the zip file")
         zipDirPath = os.path.dirname(fileName)
         zip = zipfile.ZipFile(fileName, "r")
         zip.extractall(zipDirPath)
         zip.close()
         # Remove the unneeded zip file
         os.remove(fileName)
         if len((os.listdir(zipDirPath))) > 1:
             raise RuntimeError("subtitle directory should be temporary, sound two files in it")
         srtFile = os.listdir(zipDirPath)[0]
         if srtFile.endswith(".srt"):
             srtFile = os.path.join(zipDirPath,srtFile)
             
             #convert file from cp1255 to utf-8
             log(__name__, "Convering to utf-8 %s" % srtFile)
             tempFileName=srtFile+ ".tmp"
             convert_file(srtFile,tempFileName)
             shutil.copy(tempFileName,srtFile)
             os.remove(tempFileName)
         return os.path.basename(srtFile)
Beispiel #20
0
    def get_download_link(self, sub_id, option_id):
        self._confirm_download_code(sub_id, option_id)

        # Will try to download with logged in user
        download_link = self._get_download_link_with_login(sub_id, option_id)
        if download_link:
            return download_link

        log(
            __name__,
            "trying to retrieve download link with skewed generated guest token"
        )
        generated_time_skewed_guest_token = TorecGuestTokenGenerator(
            sub_id, True).generate_ticket()
        download_link = self._try_get_download_link(
            sub_id, option_id, generated_time_skewed_guest_token)
        if download_link:
            return download_link

        log(__name__,
            "trying to retrieve download link with generated guest token")
        generated_guest_token = TorecGuestTokenGenerator(
            sub_id, False).generate_ticket()
        download_link = self._try_get_download_link(sub_id, option_id,
                                                    generated_guest_token)
        if download_link:
            return download_link

        log(__name__,
            "trying to retrieve download link with guest token request")
        return self._get_download_link_with_regular_token(sub_id, option_id)
def search(item):
    best_match_id = None
    downloader = TorecSubtitlesDownloader()
    
    try:
        search_string = build_search_string(item)
        search_data = downloader.getSubtitleMetaData(search_string)
        
        log(__name__, "search_data=%s" % str(search_data))
        if search_data != None:
            best_match_id = downloader.getBestMatchID(os.path.basename(item['file_original_path']), search_data)
    except:
        log( __name__, "failed to connect to service for subtitle search")
        xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__ , __language__(32001))).encode('utf-8'))
        return
    
    list_items = []
    if search_data != None:
        for item_data in search_data.options:
            listitem = xbmcgui.ListItem(label    = "Hebrew",
                                  label2         = item_data.name,
                                  iconImage      = "0",
                                  thumbnailImage = "he",
                                  )
                                  

            url = "plugin://%s/?action=download&page_id=%s&subtitle_id=%s&filename=%s" % (__scriptid__,
                                                                        search_data.id,
                                                                        item_data.id,
                                                                        item_data.name
                                                                        )

            if best_match_id != None and item_data.id == best_match_id:
                listitem.setProperty("sync", "true")
                list_items.insert(0, (url, listitem, False,))
            else:
                list_items.append((url, listitem, False,))
    
    xbmcplugin.addDirectoryItems(handle=int(sys.argv[1]), items=list_items)
def DownloadTorecSubtitle(search_string, release, dest_dir):
    subtitles_list = []

    downloader = TorecSubtitlesDownloader()
    metadata = downloader.getSubtitleMetaData(search_string)

    for option in metadata.options:
        if release in option.name:
            subtitles_list.append({'page_id'       : metadata.id,
                                   'filename'      : option.name,
                                   'subtitle_id'   : option.id
                                })

    # If there is one match, download it
    if len(subtitles_list) == 1:
        sub = 0
    else:
        print 'Select sub : '

        for i,sub in enumerate(subtitles_list):
          print '%s) %s' % (i, sub['filename'])

        sub = int(raw_input(' > '))

    page_id = subtitles_list[sub]["page_id"]
    subtitle_id = subtitles_list[sub]["subtitle_id"]
    filename = subtitles_list[sub]["filename"]

    downloader = TorecSubtitlesDownloader()
    downloadLink =  downloader.getDownloadLink(page_id, subtitle_id, False)
    (subtitleData, subtitleName) = downloader.download(downloadLink)
    temp_dir = tempfile.mkdtemp()
    file_name = downloader.saveData('%s/%s' % (temp_dir, filename) , subtitleData, True)
    src = os.path.join(temp_dir,file_name)
    dst = os.path.join(dest_dir,file_name)
    log(__name__, "Moving file to %s" % dst)
    shutil.move(src,dst)
Beispiel #23
0
 def getSubtitleMetaData(self, movieName):
     sanitizedName = self.sanitize(movieName)
     log(__name__, "Searching for %s" % sanitizedName)
     subtitlePage = self.searchMovieName(sanitizedName)
     if subtitlePage is None:
         log(__name__, "Couldn't find relevant subtitle page")
         return None
     else:
         log(__name__, "Found relevant meta data")
         return subtitlePage
 def search(self, movie_name):
     santized_name = self.sanitize(movie_name)
     log(__name__ , "Searching for %s" % santized_name)
     subtitlePage = self.search_by_movie_name(santized_name)
     if subtitlePage is None:
         log(__name__ ,"Couldn't find relevant subtitle page")
         return None
     else:
         log(__name__ , "Found relevant meta data")
         return subtitlePage
def download(sub_id, option_id, filename, stack=False):
    result = None
    subtitle_list = []
    exts = [".srt", ".sub"]
    downloader = TorecSubtitlesDownloader()
    start_time = time.time()

    delete_old_subs()

    try:
        result = downloader.get_download_link(sub_id, option_id)
    except Exception as e:
        log(__name__,"failed to connect to service for subtitle download %s" % e)
        return subtitle_list
        
    if result is not None:
        log(__name__, "Downloading subtitles from '%s'" % result)
        
        (subtitle_data, subtitle_name) = downloader.download(result)
        (file_name, file_ext) = os.path.splitext(subtitle_name)
        archive_file = os.path.join(__temp__, "Torec%s" % file_ext)
        with open(archive_file, "wb") as subFile:
            subFile.write(subtitle_data)

        xbmc.executebuiltin(
            ('XBMC.Extract("%s","%s")' % (archive_file, __temp__,)
             ).encode('utf-8'), True)

        for file_ in xbmcvfs.listdir(__temp__)[1]:
            ufile = file_.decode('utf-8')
            log(__name__, "file=%s" % ufile)
            file_ = os.path.join(__temp__, ufile)
            if os.path.splitext(ufile)[1] in exts:
                convert_to_utf(file_)
                subtitle_list.append(file_)
      
    log(__name__, "Overall download took %f" % (time.time() - start_time))
    return subtitle_list
    def _get_download_link_with_login(self, sub_id, option_id):
        # Checking if we have cookie - if so, we will try to use it
        log(__name__, "Checking if we have cookie")
        cookie_root = 'www.torec.net'
        cookie_name = 'Torec%5FNC%5Fsite'
        if cookie_root in self.cj._cookies and \
           cookie_name in self.cj._cookies[cookie_root]['/'] and \
           self.__addon__.getSetting("username") in self.cj._cookies[cookie_root]['/'][cookie_name].value:
            log(__name__, "Cookie found. Trying to get link")
            download_link = self._try_get_download_link(sub_id, option_id, None, True)
            if download_link:
                return download_link

        # Checking if the user has credentials, if so - logging in and downloading,
        # If not (or the login failed) - failing back to guest user download
        log(__name__, "Trying to login")
        if self.login():
            log(__name__, "Logged in. Trying to get link")
            download_link = self._try_get_download_link(sub_id, option_id, None, True)
            if download_link:
                return download_link

        return None
def download(page_id, subtitle_id,filename, stack=False):
    subtitle_list = []
    exts = [".srt", ".sub"]
    
    delay = 20
    download_wait = delay
    downloader = TorecSubtitlesDownloader()
    
    try:
        # Wait the minimal time needed for retrieving the download link
        for i in range (int(download_wait)):
            result =  downloader.getDownloadLink(page_id, subtitle_id, False)
            if (result != None):
                break
            log(__name__ ,"download will start in %i seconds" % (delay,))
            delay -= 1
            time.sleep(1)
    except:
        log( __name__, "failed to connect to service for subtitle download")
        return subtitle_list
        
    if result != None:
        log(__name__ ,"Downloading subtitles from '%s'" % result)
        
        (subtitleData, subtitleName) = downloader.download(result)
        
        zip = os.path.join( __temp__, "Torec.zip")
        downloader.saveData(zip, subtitleData)

        for file in xbmcvfs.listdir(__temp__)[1]:
            log(__name__, "file=%s" % file)
            file = os.path.join(__temp__, file)
            if (os.path.splitext( file )[1] in exts):
                subtitle_list.append(file)
      
    return subtitle_list
Beispiel #28
0
def download(page_id, subtitle_id, filename, stack=False):
    subtitle_list = []
    exts = [".srt", ".sub"]

    delay = 20
    download_wait = delay
    downloader = TorecSubtitlesDownloader()

    try:
        # Wait the minimal time needed for retrieving the download link
        for i in range(int(download_wait)):
            result = downloader.getDownloadLink(page_id, subtitle_id, False)
            if (result != None):
                break
            log(__name__, "download will start in %i seconds" % (delay, ))
            delay -= 1
            time.sleep(1)
    except:
        log(__name__, "failed to connect to service for subtitle download")
        return subtitle_list

    if result != None:
        log(__name__, "Downloading subtitles from '%s'" % result)

        (subtitleData, subtitleName) = downloader.download(result)

        zip = os.path.join(__temp__, "Torec.zip")
        downloader.saveData(zip, subtitleData)

        for file in xbmcvfs.listdir(__temp__)[1]:
            log(__name__, "file=%s" % file)
            file = os.path.join(__temp__, file)
            if (os.path.splitext(file)[1] in exts):
                subtitle_list.append(file)

    return subtitle_list
    def get_download_link(self, sub_id, option_id):
        self._confirm_download_code(sub_id, option_id)

        # Will try to download with logged in user
        download_link = self._get_download_link_with_login(sub_id, option_id)
        if download_link:
            return download_link

        log(__name__, "trying to retrieve download link with skewed generated guest token")
        generated_time_skewed_guest_token = TorecGuestTokenGenerator(sub_id, True).generate_ticket()
        download_link = self._try_get_download_link(sub_id, option_id, generated_time_skewed_guest_token)
        if download_link:
            return download_link

        log(__name__, "trying to retrieve download link with generated guest token")
        generated_guest_token = TorecGuestTokenGenerator(sub_id, False).generate_ticket()
        download_link = self._try_get_download_link(sub_id, option_id, generated_guest_token)
        if download_link:
            return download_link

        log(__name__, "trying to retrieve download link with guest token request")
        return self._get_download_link_with_regular_token(sub_id, option_id)
def delete_old_subs():
    files = glob.glob(os.path.join(__temp__, u"*.srt"))
    for f in files:
        log(__name__, "deleting %s" % f)
        os.remove(f)
Beispiel #31
0
      params=params[0:len(params)-2]
    pairsofparams=cleanedparams.split('&')
    param={}
    for i in range(len(pairsofparams)):
      splitparams={}
      splitparams=pairsofparams[i].split('=')
      if (len(splitparams))==2:
        param[splitparams[0]]=splitparams[1]
                                
  return param

params = get_params()

if params['action'] == 'search' or params['action'] == 'manualsearch':
  
  log( __name__, "action '%s' called" % params['action'])
  item = {}
  item['temp']               = False
  item['rar']                = False
  item['mansearch']          = False
  item['year']               = xbmc.getInfoLabel("VideoPlayer.Year")                         # Year
  item['season']             = str(xbmc.getInfoLabel("VideoPlayer.Season"))                  # Season
  item['episode']            = str(xbmc.getInfoLabel("VideoPlayer.Episode"))                 # Episode
  item['tvshow']             = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))  # Show
  item['title']              = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))# try to get original title
  item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))# Full path of a playing file
  item['3let_language']      = []
  
  if 'searchstring' in params:
    item['mansearch'] = True
    item['mansearchstr'] = params['searchstring']     
Beispiel #32
0
    def getSubtitleData(self, movieName, resultSubtitleDirectory):
        subtitlePage = self.getSubtitleMetaData(movieName)
        # Try to choose the most relevant option according to the file name
        chosenOption = self.findChosenOption(subtitlePage.name, subtitlePage)
        if chosenOption != None:
            log(__name__, "Found the subtitle type - %s" % chosenOption)
        else:

            log(__name__, "No suitable subtitle found!")
            log(__name__, "Available options are:")
            options = enumerate(subtitlePage.options, start=1)
            for num, option in options:
                log(__name__, "\t(%d) %s" % (num, option))

            choice = int(raw_input("What subtitle do you want to download? "))
            while (choice < 0 or choice > len(subtitlePage.options)):
                log(__name__, "bad choice")
                choice = int(
                    raw_input("What subtitle do you want to download? "))

            chosenOption = subtitlePage.options[choice - 1]

        # Retrieve the download link and download the subtitle
        downloadLink = self.getDownloadLink(subtitlePage.id, chosenOption.id,
                                            subtitlePage.url)
        if (downloadLink == ""):
            log(__name__, "Download Unsuccessful!")
            return

        (subtitleData, subtitleName) = self.download(downloadLink)

        resultSubtitlePath = os.path.join(resultSubtitleDirectory,
                                          subtitleName)
        self.saveData(resultSubtitlePath, subtitleData)
    page_id = subtitles_list[sub]["page_id"]
    subtitle_id = subtitles_list[sub]["subtitle_id"]
    filename = subtitles_list[sub]["filename"]

    downloader = TorecSubtitlesDownloader()
    downloadLink =  downloader.getDownloadLink(page_id, subtitle_id, False)
    (subtitleData, subtitleName) = downloader.download(downloadLink)
    temp_dir = tempfile.mkdtemp()
    file_name = downloader.saveData('%s/%s' % (temp_dir, filename) , subtitleData, True)
    src = os.path.join(temp_dir,file_name)
    dst = os.path.join(dest_dir,file_name)
    log(__name__, "Moving file to %s" % dst)
    shutil.move(src,dst)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Download and search Torec subtitles')
    parser.add_argument('--dest', '-d', type=str, default="/tmp/",
            help='Destination directory for saving files')
    parser.add_argument('--release', '-r', type=str, default="",
            help='Search this string in the subtitle name')
    parser.add_argument('search', type=str,
            help='search argument')

    args = parser.parse_args()
    try:
        DownloadTorecSubtitle(args.search, args.release, args.dest)
    except KeyboardInterrupt:
        log(__name__, "Got Ctrl+C exiting")

def search(item):
    best_match_id = None
    downloader = TorecSubtitlesDownloader()
    subtitles_options = None
    
    start_time = time.time()

    try:
        search_start_time = time.time()
        
        if (item['mansearch'] == False):
            if item['tvshow'] != "":
                subtitles_options = downloader.search_tvshow(item['tvshow'], item['season'], item['episode'])
            else:              
                title, year = xbmc.getCleanMovieTitle(item['title'])
                subtitles_options = downloader.search_movie(title)
        else:
            item['tvshow'], item['season'], item['episode'] = check_and_parse_if_title_is_TVshow(item['title'])
            if (item['tvshow'] == "NotTVShow"):
                item['title'] = item['title'].replace("%20", "%2b") # " " to "+"
                title, year = xbmc.getCleanMovieTitle(item['title'])
                subtitles_options = downloader.search_movie(title)
            else:
                subtitles_options = downloader.search_tvshow(item['tvshow'], int(item['season']), int(item['episode']))
                                    
        log(__name__, "search took %f" % (time.time() - search_start_time))
    except Exception as e:
        log(
            __name__,
            "failed to connect to service for subtitle search %s" % e
        )
        xbmc.executebuiltin(
            (u'Notification(%s,%s)' % (__scriptname__, __language__(32001))
             ).encode('utf-8'))
        return
    
    list_items = []
    if subtitles_options:
        best_match_option_id = downloader.get_best_match_id(
            os.path.basename(item['file_original_path']), subtitles_options
        )

        for item_data in subtitles_options:
            listitem = xbmcgui.ListItem(
                label="Hebrew", label2=item_data.name, iconImage="0",
                thumbnailImage="he"
            )
            url = (
                "plugin://%s/?action=download&sub_id=%s&option_id="
                "%s&filename=%s" % (
                    __scriptid__, item_data.sub_id, item_data.option_id, item_data.name
                )
            )

            if item_data.option_id == best_match_option_id:
                log(
                    __name__, "Found most relevant option to be : %s" %
                              item_data.name
                )
                listitem.setProperty("sync", "true")
                list_items.insert(0, (url, listitem, False,))
            else:
                list_items.append((url, listitem, False,))

    xbmcplugin.addDirectoryItems(handle=int(sys.argv[1]), items=list_items)
    log(__name__, "Overall search took %f" % (time.time() - start_time))
Beispiel #35
0
        pairsofparams = cleanedparams.split('&')
        param = {}
        for i in range(len(pairsofparams)):
            splitparams = {}
            splitparams = pairsofparams[i].split('=')
            if (len(splitparams)) == 2:
                param[splitparams[0]] = splitparams[1]

    return param


params = get_params()

if params['action'] == 'search' or params['action'] == 'manualsearch':

    log(__name__, "action '%s' called" % params['action'])
    item = {}
    item['temp'] = False
    item['rar'] = False
    item['mansearch'] = False
    item['year'] = xbmc.getInfoLabel("VideoPlayer.Year")  # Year
    item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))  # Season
    item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))  # Episode
    item['tvshow'] = normalizeString(
        xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))  # Show
    item['title'] = normalizeString(
        xbmc.getInfoLabel(
            "VideoPlayer.OriginalTitle"))  # try to get original title
    item['file_original_path'] = urllib.unquote(
        xbmc.Player().getPlayingFile().decode(
            'utf-8'))  # Full path of a playing file
    def getSubtitleData(self, movieName, resultSubtitleDirectory):
        subtitlePage = self.getSubtitleMetaData(movieName)
        # Try to choose the most relevant option according to the file name
        chosenOption = self.findChosenOption(subtitlePage.name, subtitlePage)
        if chosenOption != None:
            log(__name__ ,"Found the subtitle type - %s" % chosenOption)
        else:
            
            log(__name__ ,"No suitable subtitle found!")
            log(__name__ ,"Available options are:")
            options = enumerate(subtitlePage.options, start=1)
            for num, option in options:
                log(__name__ ,"\t(%d) %s" % (num, option))
                
            choice = int(raw_input("What subtitle do you want to download? "))
            while (choice < 0 or choice > len(subtitlePage.options)):
                log(__name__ ,"bad choice")
                choice = int(raw_input("What subtitle do you want to download? "))
        
            chosenOption = subtitlePage.options[choice-1]

        # Retrieve the download link and download the subtitle
        downloadLink = self.getDownloadLink(subtitlePage.id, chosenOption.id, subtitlePage.url)
        if (downloadLink == ""):
            log(__name__ ,"Download Unsuccessful!")
            return
        
        (subtitleData, subtitleName) = self.download(downloadLink)
        
        resultSubtitlePath = os.path.join(resultSubtitleDirectory, subtitleName)
        self.saveData(resultSubtitlePath, subtitleData)
def delete_old_subs():
  files = glob.glob(os.path.join(__temp__, u"*.srt"))
  for f in files:
    log(__name__, "deleting %s" % f)
    os.remove(f)