USTVnow Command Line Stream File Generator

I’ve changed the USTVnow script from my previous post. I needed it to work without XBMC running or even installed.

The script below will login into USTVnow, grab the stream info for each channel you have access to and then write out .strm files to a directory of your choosing. To use it just change email, password, and stream_dir to your own credentials.

I have the script set to run via CRON every thirty minutes. Then I have the scripts stream_dir setup as a source in XBMC so I can play the stream files.

The script is pure Python and should run on anything that will run Python. No need to have XBMC working.

Download: ustvnow.py

7/14/15: I’ve updated the script to work with USTVNOW’s website changes.

#!/usr/bin/python
'''
    ustvnow XBMC Plugin
    Copyright (C) 2011 t0mm0

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

20131227 - Modified by Dean Vaughan - http://deanvaughan.org to work from command line and output stream files to a directory
20140610 - Modified by Dean Vaughan - http://deanvaughan.org to work without XBMC running or installed

'''
email = 'youemail'
password = 'yourpassword'
stream_dir = 'Streams'

stream_type = 'rtmp'
quality = '1'

import cookielib
import os
import re
import urllib, urllib2
import sys

class Ustvnow:
    __BASE_URL = 'http://lv2.ustvnow.com'
    def __init__(self, user, password):
        self.user = user
        self.password = password

    def get_channels(self, quality=1, stream_type='rtmp'):
        self._login()
        html = self._get_html('iphone_ajax', {'tab': 'iphone_playingnow',
                                              'token': self.token})
        channels = []
        for channel in re.finditer('class="panel".+?title="(.+?)".+?src="' +
                                   '(.+?)".+?class="nowplaying_item">(.+?)' +
                                   '<\/td>.+?class="nowplaying_itemdesc".+?' +
                                   '<\/a>(.+?)<\/td>.+?href="(.+?)"',
                                   html, re.DOTALL):
            name, icon, title, plot, url = channel.groups()

            #tmp work around till ustvnow stablizes changes
            name = name.replace('\n','').replace('\t','').replace('\r','').replace('<fieldset> ','').replace('<div class=','').replace('>','').replace('"','').replace(' ','')
            if not name:
                name = ((icon.rsplit('/',1)[1]).replace('.png','')).upper()
                name = name.replace('WLYH','CW').replace('WHTM','ABC').replace('WPMT','FOX').replace('WPSU','PBS').replace('WHP','CBS').replace('WGAL','NBC').replace('WHVLLD','MY9')

            try:
                if not url.startswith('http'):
                    now = {'title': title, 'plot': plot.strip()}
                    url = '%s%s%d' % (stream_type, url[4:-1], quality + 1)

                   # if self.premium == False:
                   #     if name not in ['CW','ABC','FOX','PBS','CBS','NBS','MY9']:
                   #         raise

                    print name
                    channels.append({'name': name, 'url': url,
                                   'icon': icon, 'now': now})
            except:
                pass
        return channels


    def _build_url(self, path, queries={}):
        if queries:
            query = build_query(queries)
            return '%s/%s?%s' % (self.__BASE_URL, path, query)
        else:
            return '%s/%s' % (self.__BASE_URL, path)

    def _fetch(self, url, form_data=False):
        if form_data:
            req = urllib2.Request(url, form_data)
        else:
            req = url
        try:
            response = urllib2.urlopen(url)
            return response
        except urllib2.URLError, e:
            return False

    def _get_html(self, path, queries={}):
        html = False
        url = self._build_url(path, queries)

        response = self._fetch(url)
        if response:
            html = response.read()
        else:
            html = False

        return html

    def _login(self):
        self.token = None
        self.cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))

        urllib2.install_opener(opener)
        url = self._build_url('iphone_login', {'username': self.user,
                                               'password': self.password})
        response = self._fetch(url)
        #response = opener.open(url)

        for cookie in self.cj:
            if cookie.name == 'token':
                self.token = cookie.value

def build_query(queries):
    return '&amp;'.join([k+'='+urllib.quote(str(v)) for (k,v) in queries.items()])

ustv = Ustvnow(email, password)
channels = ustv.get_channels(int(quality), stream_type)

if(len(channels)):
    old_streams = os.listdir(stream_dir)
    for old_stream in old_streams:
        if 'USTV-' in old_stream:
          os.remove(stream_dir + '/' + old_stream)

for c in channels:
    title = c['now']['title']
    title = re.sub('[^\w\-_\. ]', '', title)
    title = title.replace(' amp ', ' and ')
    f = open(stream_dir + '/USTV-' + c['name'] + ': ' + title + '.strm', 'w')
    f.write(c['url'])
    f.close()
                  

62 comments

  1. This is great, exactly what I’ve been looking for. Do you think the same thing is possible with other xbmc plugins such as ilive or filmon?

    1. Short answer is probably, long answer would be really long.

      The guy who wrote the original USTVNow plugin did a good job on it. The code was easy to understand and straight forward. There wasn’t much to it in regards to picking it apart so it created files instead of an XBMC menu.

      I’m sure the concept is something you could apply to other plugins, but the actual implementation of such could be difficult.

  2. Windows doesn’t allow colons in file names. If you’re running this on Windows you’ll need to change:

    f = open(stream_dir + ‘/USTV-‘ + c[‘name’] + ‘: ‘ + title + ‘.strm’, ‘w’)

    To

    f = open(stream_dir + ‘/USTV-‘ + c[‘name’] + ‘ ‘ + title + ‘.strm’, ‘w’)

  3. is there anyway i can modified this to play my own rtmp streams found on internet so anyone with my own version ustvnow app will be able to view my own streams? please help me

        1. ok tried using it but issue i am getting i can see is the stream folder…

          if i put:
          C:\Documents and Settings\settop\Desktop\New Folder\Streams

          it shows up in the Python editor as:
          C:\\Documents and Settings\\settop\\Desktop\\New Folder\\Streams

          is this right? cause i am getting no errors but i am also not getting an .strm files made in that folder.

          also i do have just a free account with ustvnow will that make a difference?

          1. Perfect got everything working great thanks! using the portable Python is perfect.

            do they change the URL’s often?

  4. Something is wrong here πŸ™

    this is error i am getting…

    Traceback (most recent call last):
    File “ustvnow.py”, line 110, in
    channels = ustv.get_channels(int(quality), stream_type)
    File “ustvnow.py”, line 51, in get_channels
    html, re.DOTALL):
    File “C:\Documents and Settings\settop\Desktop\IPTV My Way\Plugins\Python\App\
    lib\re.py”, line 186, in finditer
    return _compile(pattern, flags).finditer(string)
    TypeError: expected string or buffer
    File Not Found
    Could Not Find C:\Documents and Settings\settop\Desktop\IPTV My Way\Plugins\USTV
    Now\tmp\*.tmp

  5. you seem to be a master at this! and i keep trying to get this to work but can you tell me how i could jsut change the code to put all links into one file? im just going to play in VLC

    1. Change this:

      for c in channels:
      title = c[‘now’][‘title’]
      title = re.sub(‘[^\w\-_\. ]’, ”, title)
      title = title.replace(‘ amp ‘, ‘ and ‘)
      f = open(stream_dir + ‘/USTV-‘ + c[‘name’] + ‘: ‘ + title + ‘.strm’, ‘w’)
      f.write(c[‘url’] + “\n”)
      f.close()

      To:

      for c in channels:
      f = open(stream_dir + ‘/USTV.strm’, ‘a’)
      f.write(c[‘url’])
      f.close()

      Or something like that.

        1. I think the comments form is mangling up my code. Make sure the f.write line has four spaces in front of it.

          f = open(stream_dir + β€˜/USTV.strm’, β€˜a’)
          for c in channels:
          f.write(c[‘url’])

          f.close()

  6. Anybody else having problem with playing the links generated. They worked perfectly a few hours ago but now they just lock up every player I try. VLC get so stuck that I must force it to stop. On the USTVnow website the embedded player works fine…

  7. Can you do it for the new addon plugin.video.stalker-master.zip Its 2 files in python. Its showing the titles in the Video addon. I Just want to print the file with the link like you did on the ustvnow.

    I dont know where to look for. Maybe you can give me a pointer or 2.

  8. Dean, this is fantastic — thanks much for the update! I’ve currently got this running on my NAS (scheduled nightly), and point my FireTV to the streams from within the KODI TV Guide add-on. All works beautifully, but in the interest of portability, I’d love to run your script directly on the FireTV itself (scheduled nightly). Is this possible?

  9. Actually Dean, running it on the FireTV turns out to be very easy to do!

    As a proof of concept, I installed QPyPlus for Android:
    https://play.google.com/store/apps/details?id=com.hipipal.qpyplus&hl=en

    I added your script to the QPyPlus scripts folder with this path:
    /storage/emulated/0/USTVStreams

    then, I added that path to my video sources in KODI.
    The script ran perfectly the first time, and the strm files are accessible to the EPG in the KODI TV Guide add-on.

    I haven’t yet figured out how to schedule this, but running it this way is so easy that I may not bother. The program requires a mouse to set it up, but once that’s done, you can just make the script the default, so it can all be done with the remote.

      1. OK, it’s actually SOOOO much easier than that. In reading the KODI documentation, it turns out you can auto-run a script at startup, just by naming it “autoexec.py” and putting it in the root of your userdata folder! In addition, you can map the running of a script to a key on your remote with the keyboard.xml file like so:

        RunScript("special://masterprofile/USTVStreamGen.py")

        I’ve done both, and it works perfectly. Thanks again for the original script!

        1. By the way, my incentive for this, was that USTV is now incorporating a 3-digit number as part of the stream that is based on the external IP of your network. When I was doing this on my NAS, the problem was that the generated streams only worked on my local network. Now they’ll work anywhere.

  10. Hey Thank you for the great script i am desperately trying to get it work i know the url generated are good i get every channel file and url but when i try to play the url in vlc it does not play does anyone had similar, the http steam from the website works good its only the rtmp stream that is not working.

  11. so i guess i may have found the issue when i try to use lv2 the streams doesn’t work but they work with lv7 and lv9 base url

  12. USTVNOW was down over the weekend. I think they changed something because your ustvnow.py script doesn’t work anymore. It won’t connect. Hope you have the time to fix it. Thanks a lot for writing it.

      1. Sorry, No I didn’t get it working. I was using the Official USTVNOW kodi plugin. So your ustvnow.py runs fine but it won’t work in kodi. Says it’s not connecting.

  13. I’m trying to use your script here but the generated files are all zero bytes… Am I missing something here? I do have changed the email, password and dir name before runing it.

  14. I’ve been having issues playing the links that the script spits out. Everything is correct, user name/pw etc.. just can’t play the streaming links. I’ve tried using xbmc with the .strm files and I’ve also tried with vlc using the extracted rtmp link. Does anyone have any insight?

      1. So is there any word on the update for this? I noticed that the streams are now… with names like rtmp://ilv51.is.ustvnow.com:1935/ilv51?key=
        rtmp://ilv52.is.ustvnow.com:1935/ilv52?key=
        rtmp://ilv53.is.ustvnow.com:1935/ilv53?key=
        rtmp://ilv61.is.ustvnow.com:1935/ilv61?key=

  15. Yes, the script fails now. The good news is, the new USTV streams are far less restrictive than the old ones. Previously, the created links only worked on the same network on which they were created (tied to the IP address ). Now, you can create a link that will generate a program guide that will work on any network. There are two distinct streams possible, 1 for computer and 1 for mobile devices. The USTVNow Plus plugin for Kodi works fine, but I’d still love a python script so I could generate the stream files for use in my EPG.

    Dean, any chance you could look at the new stuff and modify your script? I know how to manually generate the URLs but not how to automate the process in python. TIA.

    1. ustvnowplus works, but it is SO slow compared with opening the stream directly the way we did before. Can no one figure out how to make this work?

        1. Thank for the script. Script works good. Is there a way to change the quality? Right now the script only plays HD.

Leave a Reply to Dean Vaughan Cancel reply

Your email address will not be published. Required fields are marked *