Example #1
0
def addFolder(folder):
        keyboard = xbmc.Keyboard('','[B][COLOR=FF67cc33]Enter Folder Name[/COLOR][/B]')
        keyboard.doModal()
        if (keyboard.isConfirmed() == False):
            return
        else:
            name = keyboard.getText()
            if name != '':
                if selfAddon.getSetting("folderthumb") == "true":
                    thumb = xbmcgui.Dialog().browse(2, "[B][COLOR=FF67cc33]Thumbnail File Location[/COLOR][/B]", browseType)
                else:
                    thumb= ''
                if selfAddon.getSetting("folderfanart") == "true":
                    fanart = xbmcgui.Dialog().browse(2, "[B][COLOR=FF67cc33]Fanart File Location[/COLOR][/B]", browseType)
                else:
                    fanart=''
                folders = {}
                folders['name'] = urllib.quote_plus(name)
                folders['place'] = ''
                folders['fanart'] = urllib.quote_plus(fanart)
                folders['folder'] = urllib.quote_plus(folder)
                folders['thumb'] = urllib.quote_plus(thumb)
                folders['placeb'] = ''
                if not os.path.exists(FolderFile):
                    open(FolderFile,'w').write(str(folders))
                    xbmc.executebuiltin("XBMC.Notification([B][COLOR=FF67cc33]"+name+"[/COLOR][/B],[B]Folder Created.[/B],3000,"")")
                else:
                    open(FolderFile,'a').write(str(folders))
                    xbmc.executebuiltin("XBMC.Notification([B][COLOR=FF67cc33]"+name+"[/COLOR][/B],[B]Folder Created.[/B],3000,"")")
                xbmc.executebuiltin("Container.Refresh")
            else:
                xbmc.executebuiltin("XBMC.Notification([B][COLOR=FF67cc33]Sorry![/COLOR][/B],[B]Invalid entry[/B],3000,"")")
            return
Example #2
0
def addDir(name,url,mode,iconimage,itemcount,isFolder=False):
        try:
          if not 'COLOR' in name:
            splitName=name.partition('(')
            simplename=""
            simpleyear=""
            if len(splitName)>0:
                simplename=splitName[0]
                simpleyear=splitName[2].partition(')')
            if len(simpleyear)>0:
                simpleyear=simpleyear[0]
            mg = metahandlers.MetaData()
            meta = mg.get_meta('movie', name=simplename ,year=simpleyear)
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url'])
            liz.setInfo( type="Video", infoLabels= meta )
            liz.setProperty("IsPlayable","true")
            contextMenuItems = []
            contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
            liz.addContextMenuItems(contextMenuItems, replaceItems=False)
            if not meta['backdrop_url'] == '': liz.setProperty('fanart_image', meta['backdrop_url'])
            else: liz.setProperty('fanart_image', fanart)
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder,totalItems=itemcount)
            return ok
        except:
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
            liz.setInfo( type="Video", infoLabels={ "Title": name } )
            liz.setProperty('fanart_image', fanart)
            liz.setProperty("IsPlayable","true")
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
            return ok
Example #3
0
def addDir(name, url, mode, iconimage, pagina, tipo=False, infoLabels=False, poster=False):
    if infoLabels:
        infoLabelsAux = infoLabels
    else:
        infoLabelsAux = {'Title': name}

    if poster:
        posterAux = poster
    else:
        posterAux = iconimage

    u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&pagina=" + str(pagina) + "&mode=" + str(
        mode) + "&name=" + urllib.quote_plus(name)
    ok = True

    if tipo == 'filme':
        xbmcplugin.setContent(int(sys.argv[1]), 'Movies')
    elif tipo == 'serie':
        xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
    elif tipo == 'episodio':
        xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    else:
        xbmcplugin.setContent(int(sys.argv[1]), 'Movies')

    liz = xbmcgui.ListItem(name, iconImage=posterAux, thumbnailImage=posterAux)
    liz.setProperty('fanart_image', posterAux)
    liz.setInfo(type="Video", infoLabels=infoLabelsAux)

    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
    return ok
Example #4
0
def encode_multipart_formdata(fields, files):
    """
    refer from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572202

    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return (content_type, body) ready for httplib.HTTP instance
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(urllib.quote_plus(str(value)))
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, urllib.quote_plus(filename)))
        L.append('Content-Type: %s' % get_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
Example #5
0
def prepare_url(values):
    vals = DEFAULT_VALUES.copy()
    vals.update(values)
    vals["query"] = quote_plus(vals["query"])
    vals["query2"] = quote_plus(vals["query2"])
    return (
        "http://vls2.icm.edu.pl/cgi-bin/search.pl?SearchTemplate=search_form.advanced"
        + "&search_field=%(query)s"
        + "&fields=%(query-fields)s"
        + "&AdvBooleanJoiner=%(query-join)s"
        + "&search_field2=%(query2)s"
        + "&fields2=%(query2-fields)s"
        + "&Database=elsevier_1990"
        + "&Database=springer_1990"
        + "&Category=all_categories"
        + "&ArticleType=All+Types..."
        + "&Language="
        + "&daterange=yearrange"
        + "&fromyear=%(from)d"
        + "&toyear=%(to)d"
        + "&Max=%(num)d"
        + "&Start=%(start)d"
        + "&Order="
        + "&GetSearchResults=Submit+Query"
    ) % vals
Example #6
0
    def __init__(self, words):
        self.url = ('/search?q=%s&btnI=%s' %
	            (urllib.quote_plus(' '.join(words)),
	             urllib.quote_plus("I'm Feeling Lucky")))
        self.agent="Twisted/GoogleChecker"
        self.host = "www.google.com"
        self.deferred = defer.Deferred()
Example #7
0
def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
Example #8
0
def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
  def _edit(self, folder=None, file=None):
    # set some vars
    files = None
    success = None

    # check for folder
    if folder:
      # check for the homepage file
      if file:
        # update the site
        success = self._update(folder, file)

      # get files in the folder
      files = self._make_req('https://www.googleapis.com/drive/v2/files?q=' +
        urllib.quote_plus('"%s" in parents and mimeType = "application/vnd.google-apps.document"' % folder))['items']

    # get the root folders
    folders = self._make_req('https://www.googleapis.com/drive/v2/files?q=' +
      urllib.quote_plus('"root" in parents and mimeType = "application/vnd.google-apps.folder"'))['items']

    # load the view
    template = template_helper.load('admin', {
      'folders': folders,
      'files': files,
      'success': success,
      'self_url': self.request.uri
    })

    self.response.out.write(template)
Example #10
0
def sign_s3():
    # Load necessary information into the application:
    AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
    AWS_SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
    S3_BUCKET = os.environ.get('S3_BUCKET')

    # Collect information on the file from the GET parameters of the request:
    object_name = urllib.quote_plus(request.args.get('file_name'))
    mime_type = request.args.get('file_type')

    # Set the expiry time of the signature (in seconds) and declare the permissions of the file to be uploaded
    expires = int(time.time()+60*60*24)
    amz_headers = "x-amz-acl:public-read"
 
    # Generate the StringToSign:
    string_to_sign = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)

    # Generate the signature with which the StringToSign can be signed:
    signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, string_to_sign.encode('utf8'), sha1).digest())
    # Remove surrounding whitespace and quote special characters:
    signature = urllib.quote_plus(signature.strip())

    # Build the URL of the file in anticipation of its imminent upload:
    url = 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, object_name)

    
    content = json.dumps({
        'signed_request': '%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
        'url': url,
    })
   
    return content
Example #11
0
def addDir(name, url, mode, iconimage, description, isFolder=True, channelName=None, background=None, isTvGuide=False, channelID=None, categoryID=None):
	chName = channelName if channelName is not None else ""
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description} )
	

	if mode==3 or mode==4 or mode==7 or mode==8 or mode==10 or mode==11 or mode==99:
		isFolder=False
	
	if mode==3 or mode==4 or mode==10 or mode==11:
		liz.setProperty("IsPlayable","true")
		items = []

		if mode == 3:
			items.append((localizedString(30205).encode('utf-8'), 'XBMC.Container.Update({0}?url={1}&mode=9&iconimage={2}&displayname={3}&categoryid={4})'.format(sys.argv[0], urllib.quote_plus(url), iconimage, channelName, categoryID)))
			items.append((localizedString(30206).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&categoryid={2}&mode=17)'.format(sys.argv[0], channelID, categoryID)))
		elif mode == 4:
			items.append((localizedString(30205).encode('utf-8'), 'XBMC.Container.Update({0}?url={1}&mode=9&iconimage={2}&displayname={3}&categoryid={4})'.format(sys.argv[0], urllib.quote_plus(url), iconimage, channelName, categoryID)))
			items.append((localizedString(30207).encode('utf-8'), "XBMC.RunPlugin({0}?url={1}&mode=18)".format(sys.argv[0], channelID)))
			items.append((localizedString(30021).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=-1)'.format(sys.argv[0], channelID)))
			items.append((localizedString(30022).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=1)'.format(sys.argv[0], channelID)))
			items.append((localizedString(30023).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=0)'.format(sys.argv[0], channelID)))
		elif mode == 10:
			if isTvGuide:
				items.append((localizedString(30205).encode('utf-8'), 'XBMC.Container.Update({0}?url={1}&mode=5&iconimage={2}&name={3}&categoryid={4})'.format(sys.argv[0], urllib.quote_plus(url), iconimage, channelName, categoryID)))
			items.append((localizedString(30206).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&categoryid={2}&mode=17)'.format(sys.argv[0], channelID, categoryID)))
		elif mode == 11:
			if isTvGuide:
				items.append((localizedString(30205).encode('utf-8'), 'XBMC.Container.Update({0}?url={1}&mode=5&iconimage={2}&name={3}&categoryid={4})'.format(sys.argv[0], urllib.quote_plus(url), iconimage, channelName, categoryID)))
			items.append((localizedString(30207).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=18)'.format(sys.argv[0], channelID)))
			items.append((localizedString(30021).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=-1)'.format(sys.argv[0], channelID)))
			items.append((localizedString(30022).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=1)'.format(sys.argv[0], channelID)))
			items.append((localizedString(30023).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=41&iconimage=0)'.format(sys.argv[0], channelID)))

		liz.addContextMenuItems(items = items)
		
	elif mode == 2:
		liz.addContextMenuItems(items = 
			[(localizedString(30210).encode('utf-8'), 'XBMC.Container.Update({0}?mode=37&categoryid={1})'.format(sys.argv[0], urllib.quote_plus(channelName))),
			(localizedString(30212).encode('utf-8'), 'XBMC.Container.Update({0}?mode=38&categoryid={1})'.format(sys.argv[0], urllib.quote_plus(channelName))),
			(localizedString(30021).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=42&iconimage=-1)'.format(sys.argv[0], channelID)),
			(localizedString(30022).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=42&iconimage=1)'.format(sys.argv[0], channelID)),
			(localizedString(30023).encode('utf-8'), 'XBMC.RunPlugin({0}?url={1}&mode=42&iconimage=0)'.format(sys.argv[0], channelID))
			])
		
	elif mode == 16:
		liz.addContextMenuItems(items = 
			[(localizedString(30211).encode('utf-8'), 'XBMC.Container.Update({0}?mode=39)'.format(sys.argv[0])),
			(localizedString(30213).encode('utf-8'), 'XBMC.Container.Update({0}?mode=40)'.format(sys.argv[0]))])
	
	if background is not None:
		liz.setProperty("Fanart_Image", background)

	fullUrl = "{0}?url={1}&mode={2}&name={3}&iconimage={4}&description={5}".format(sys.argv[0], urllib.quote_plus(url), mode, urllib.quote_plus(name), urllib.quote_plus(iconimage), urllib.quote_plus(description))
	if channelName is not None:
		fullUrl = "{0}&displayname={1}".format(fullUrl, urllib.quote_plus(channelName))
	if categoryID is not None:
		fullUrl = "{0}&categoryid={1}".format(fullUrl, urllib.quote_plus(categoryID))
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=fullUrl, listitem=liz, isFolder=isFolder)
	return ok
Example #12
0
 def instance_url(self):
     self.id = util.utf8(self.id)
     self.fee = util.utf8(self.fee)
     base = ApplicationFee.class_url()
     cust_extn = urllib.quote_plus(self.fee)
     extn = urllib.quote_plus(self.id)
     return "%s/%s/refunds/%s" % (base, cust_extn, extn)
Example #13
0
def set_proxy():
    proxy = os.getenv('PROXY', '')
    if proxy:
        interface_ip_list = get_all_interface_ip()
        predefine_no_proxy_list = ".xip.io,172.30.0.0/16,172.17.0.0/16,%s" % socket.gethostname()
        proxy_user = quote_plus(os.getenv('PROXY_USER',''))
        if proxy_user:
            proxy_password = quote_plus(os.getenv('PROXY_PASSWORD',''))
            http_proxy_url = "http://%s:%s@%s" % (proxy_user, proxy_password, proxy)
            https_proxy_url = "https://%s:%s@%s" % (proxy_user, proxy_password, proxy)
        else:
            http_proxy_url = "http://%s" % proxy
            https_proxy_url = "https://%s" % proxy
        # openshift proxy setup
        if system(('sed -i -e "/^#HTTP_PROXY=*/cHTTP_PROXY=%s"'
                   ' -e "/^#HTTPS_PROXY=*/cHTTPS_PROXY=%s"'
                   ' -e "/^#NO_PROXY=*/cNO_PROXY=%s%s"'
                ' %s') % (http_proxy_url, http_proxy_url, interface_ip_list,
                          predefine_no_proxy_list, OPENSHIFT_OPTION))[2]:
            return ("Permisison denined: %s" % OPENSHIFT_OPTION)
        # docker daemon proxy setup
        if not os.path.isdir('/etc/systemd/system/docker.service.d'):
            subprocess.call("mkdir /etc/systemd/system/docker.service.d", shell=True)
        env_file_content = ('[Service]\n'
                'Environment="HTTP_PROXY=%s" "NO_PROXY=localhost,127.0.0.1,::1,.xip.io"\n') \
                        % (http_proxy_url)
        try:
            with open('/etc/systemd/system/docker.service.d/http-proxy.conf', 'w') as fh:
                fh.write(env_file_content)
            subprocess.call('systemctl daemon-reload', shell=True)
            return subprocess.call('systemctl restart docker', shell=True)
        except IOError as err:
            return err
Example #14
0
 def instance_url(self):
     self.id = util.utf8(self.id)
     self.charge = util.utf8(self.charge)
     base = Charge.class_url()
     cust_extn = urllib.quote_plus(self.charge)
     extn = urllib.quote_plus(self.id)
     return "%s/%s/refunds/%s" % (base, cust_extn, extn)
Example #15
0
 def instance_url(self):
     self.id = util.utf8(self.id)
     self.charge = util.utf8(self.transfer)
     base = Transfer.class_url()
     cust_extn = urllib.quote_plus(self.transfer)
     extn = urllib.quote_plus(self.id)
     return "%s/%s/reversals/%s" % (base, cust_extn, extn)
Example #16
0
 def test_default_quoting(self):
     # Make sure all characters that should be quoted are by default sans
     # space (separate test for that).
     should_quote = [chr(num) for num in range(32)]  # For 0x00 - 0x1F
     should_quote.append('<>#%"{}|\^[]`')
     should_quote.append(chr(127))  # For 0x7F
     should_quote = "".join(should_quote)
     for char in should_quote:
         result = urllib.quote(char)
         self.assertEqual(
             hexescape(char),
             result,
             "using quote(): %s should be escaped to %s, not %s" % (char, hexescape(char), result),
         )
         result = urllib.quote_plus(char)
         self.assertEqual(
             hexescape(char),
             result,
             "using quote_plus(): " "%s should be escapes to %s, not %s" % (char, hexescape(char), result),
         )
     del should_quote
     partial_quote = "ab[]cd"
     expected = "ab%5B%5Dcd"
     result = urllib.quote(partial_quote)
     self.assertEqual(expected, result, "using quote(): %s != %s" % (expected, result))
     result = urllib.quote_plus(partial_quote)
     self.assertEqual(expected, result, "using quote_plus(): %s != %s" % (expected, result))
     self.assertRaises(TypeError, urllib.quote, None)
Example #17
0
    def instance_url(self):
        self.id = util.utf8(self.id)
        extn = urllib.quote_plus(self.id)
        if hasattr(self, "customer"):
            customer = util.utf8(self.customer)

            base = Customer.class_url()
            owner_extn = urllib.quote_plus(customer)
            class_base = "sources"

        elif hasattr(self, "recipient"):
            recipient = util.utf8(self.recipient)

            base = Recipient.class_url()
            owner_extn = urllib.quote_plus(recipient)
            class_base = "cards"

        elif hasattr(self, "account"):
            account = util.utf8(self.account)

            base = Account.class_url()
            owner_extn = urllib.quote_plus(account)
            class_base = "external_accounts"

        else:
            raise error.InvalidRequestError(
                "Could not determine whether card_id %s is "
                "attached to a customer, recipient, or "
                "account." % self.id,
                "id",
            )

        return "%s/%s/%s/%s" % (base, owner_extn, class_base, extn)
Example #18
0
def addDir(name, url, mode, iconimage, description):
    u = (
        sys.argv[0]
        + "?url="
        + urllib.quote_plus(url)
        + "&mode="
        + str(mode)
        + "&name="
        + urllib.quote_plus(name)
        + "&iconimage="
        + urllib.quote_plus(iconimage)
        + "&description="
        + urllib.quote_plus(description)
    )
    ok = True
    liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
    liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": description})
    if mode == 1:
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz)
    elif mode == 3 or mode == 5:
        liz.setProperty("IsPlayable", "true")
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
    else:
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
    return ok
def addDir(title, url, mode, page=0, searchValue=''):
    sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) + \
              '&mode=' + urllib.quote_plus(str(mode)) + '&page=' + urllib.quote_plus(str(page))+'&search'+\
              urllib.quote_plus(str(searchValue))

    item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage='')
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=True)
Example #20
0
 def instance_url(self):
     token = util.utf8(self.id)
     transfer = util.utf8(self.transfer)
     base = Transfer.class_url()
     cust_extn = urllib.quote_plus(transfer)
     extn = urllib.quote_plus(token)
     return "%s/%s/reversals/%s" % (base, cust_extn, extn)
Example #21
0
def addVideoDirR(name, url, mode, iconimage, videoType="", desc="", duration="", year="", mpaa="", director="", genre="", rating=""):
    filename = (''.join(c for c in unicode(url, 'utf-8') if c not in '/\\:?"*|<>')).strip()+".jpg"
    coverFile = os.path.join(cacheFolderCoversTMDB, filename)
    fanartFile = os.path.join(cacheFolderFanartTMDB, filename)
    if os.path.exists(coverFile):
        iconimage = coverFile
    u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&thumb="+urllib.quote_plus(iconimage)
    ok = True
    liz = xbmcgui.ListItem(name, iconImage="DefaultTVShows.png", thumbnailImage=iconimage)
    liz.setInfo(type="video", infoLabels={"title": name, "plot": desc, "duration": duration, "year": year, "mpaa": mpaa, "director": director, "genre": genre, "rating": rating})
    if os.path.exists(fanartFile):
        liz.setProperty("fanart_image", fanartFile)
    elif os.path.exists(coverFile):
        liz.setProperty("fanart_image", coverFile)
    entries = []
    entries.append((translation(30134), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=playTrailer&url='+urllib.quote_plus(name)+')',))
    entries.append((translation(30115), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=removeFromQueue&url='+urllib.quote_plus(url)+')',))
    if videoType == "tvshow":
        entries.append((translation(30122), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=addSeriesToLibrary&url=&name='+str(name.strip())+'&seriesID='+str(url)+')',))
        if browseTvShows:
            entries.append((translation(30121), 'Container.Update(plugin://plugin.video.netflixbmc/?mode=playVideo&url='+urllib.quote_plus(url)+'&thumb='+urllib.quote_plus(iconimage)+')',))
        else:
            entries.append((translation(30118), 'Container.Update(plugin://plugin.video.netflixbmc/?mode=listSeasons&url='+urllib.quote_plus(url)+'&thumb='+urllib.quote_plus(iconimage)+')',))
    elif videoType == "movie":
        entries.append((translation(30122), 'RunPlugin(plugin://plugin.video.netflixbmc/?mode=addMovieToLibrary&url='+urllib.quote_plus(url)+'&name='+str(name.strip()+' ('+year+')')+')',))
    liz.addContextMenuItems(entries)
    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
    return ok
Example #22
0
 def add(self, service, name, category, title, iconimage, url, desc, page, folder=True, isPlayable=True):
     u = (
         sys.argv[0]
         + "?service="
         + service
         + "&name="
         + name
         + "&category="
         + category
         + "&title="
         + title
         + "&url="
         + urllib.quote_plus(url)
         + "&icon="
         + urllib.quote_plus(iconimage)
         + "&page="
         + urllib.quote_plus(page)
     )
     # log.info(str(u))
     if name == "main-menu" or name == "categories-menu":
         title = category
     if iconimage == "":
         iconimage = "DefaultVideo.png"
     liz = xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
     liz.setProperty("fanart_image", iconimage)
     if isPlayable:
         liz.setProperty("IsPlayable", "true")
     liz.setInfo(
         type="Video", infoLabels={"Title": title, "Plot": desc, "Episode": "AAA", "Year": "2000", "Genre": "bbb"}
     )
     xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=folder)
Example #23
0
    def build_rest_path(self, bucket=None, key=None, params=None, prefix=None) :
        """
        Given a RiakClient, RiakBucket, Key, LinkSpec, and Params,
        construct and return a URL.
        """
        # Build 'http://hostname:port/prefix/bucket'
        path = ''
        path += '/' + (prefix or self._prefix)

        # Add '.../bucket'
        if bucket is not None:
            path += '/' + urllib.quote_plus(bucket._name)

        # Add '.../key'
        if key is not None:
            path += '/' + urllib.quote_plus(key)

        # Add query parameters.
        if params is not None:
            s = ''
            for key in params.keys():
                if s != '': s += '&'
                s += urllib.quote_plus(key) + '=' + urllib.quote_plus(str(params[key]))
            path += '?' + s

        # Return.
        return self._host, self._port, path
Example #24
0
def addDirectoryItem(name, url, mode, label2='', infoType="Music", infoLabels = {}, isFolder=True):
    liz=xbmcgui.ListItem(name, label2)
    if not infoLabels:
        infoLabels = {"Title": name }
    liz.setInfo( infoType, infoLabels )
    
    v = "?name=%s&url=%s" % (urllib.quote_plus(name.encode('utf-8')), urllib.quote_plus(url.encode('utf-8')), )
    action1 = 'XBMC.RunPlugin(plugin://plugin.audio.listenliveeu/?add%s%s)' % (v, '\n')
    action2 = 'XBMC.RunPlugin(plugin://plugin.audio.listenliveeu/?remfav%s%s)' % (v, '\n')
    action3 = 'XBMC.RunPlugin(plugin://plugin.audio.listenliveeu/?removeall)'
    
    if mode==2:
        try:
            liz.addContextMenuItems([(__language__(30004), action1), (__language__(30006), action3)])
        except:
            errorOK("addDirectoryItem()")
        
    elif mode==3:
        try:
            liz.addContextMenuItems([(__language__(30005), action2), (__language__(30006), action3)])
        except:
            errorOK("addDirectoryItem()")

    u = "%s?url=%s&mode=%s&name=%s" % (sys.argv[0], urllib.quote_plus(url), mode, urllib.quote_plus(name.encode('utf-8')), )
    log("%s" % u)
    return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
    def __call__(self, r):
        # modify and return the request
    
        parsed = urlparse.urlparse(r.url)
        url = parsed.geturl().split('?',1)[0]
        url_params= urlparse.parse_qs(parsed.query)
        
        #normalize the list value
        for param in url_params:
            url_params[param] = url_params[param][0]
        
        url_params['apikey'] = self.apikey
        
        keys = sorted(url_params.keys())

        sig_params = []
        for k in keys:
            sig_params.append(k + '=' + urllib.quote_plus(url_params[k]).replace("+", "%20"))
       
        query = '&'.join(sig_params)

        signature = base64.b64encode(hmac.new(
            self.secretkey,
            msg=query.lower(),
            digestmod=hashlib.sha1
        ).digest())

        
        query += '&signature=' + urllib.quote_plus(signature)

        r.url = url + '?' + query
        
        return r
Example #26
0
def connect():
    """
    Test the given login/password agains't the database
    If it's ok, save them encrypted in the session
    and return the state of the connection
    """
    try:
        values = {
            'engine':   request.form['server-engine'],
            'username': urllib.quote_plus(request.form['username']),
            'password': urllib.quote_plus(request.form['password']) if 'password' in request.form else '',
            'host':     urllib.quote_plus(request.form['server-hostname']),
            'port':     int(request.form['server-port'])
        }

        cnx = create_engine('%s://%s:%s@%s:%d' % (
                                values['engine'],
                                values['username'],
                                values['password'],
                                values['host'],
                                values['port'],
                            ))
        cnx.connect()

        token = uuid.uuid4().hex
        g.session = session_store.create(request, token, values)
        
        return jsonify({
            'token': token,
            'expire': mktime(g.session.expire.timetuple())
        })
    except OperationalError as e:
        response = jsonify ({'code': e.orig[0], 'message': e.orig[1]})
        response.status_code = 400
        return response
Example #27
0
def addDir(title, url, mode):
    sys_url = sys.argv[0] + '?title=' + urllib.quote_plus(title) + '&url=' + urllib.quote_plus(url) + '&mode=' + urllib.quote_plus(str(mode))

    item = xbmcgui.ListItem(title, iconImage='DefaultFolder.png', thumbnailImage='')
    item.setInfo( type='Video', infoLabels={'Title': title} )

    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sys_url, listitem=item, isFolder=True)
Example #28
0
    def query_lastfm(self, artist, title):
        """Use track.getinfo to get track metadata. If it fails, fall back on
        track.search"""
        encoded_artist = quote_plus(artist.encode('utf-8'))
        encoded_title = quote_plus(title.encode('utf-8'))
        track_info = self.getinfo(encoded_artist, encoded_title)
        if not track_info:
            track_info = self.tracksearch(encoded_artist, encoded_title)
            if not track_info:
                return None
            fixed_artist = track_info['artist'][:256]
            fixed_title = track_info['name'][:256]
            mbid = track_info['mbid']
            toptags = self.get_tags(mbid)
        else:
            fixed_artist = track_info['artist']['name'][:256]
            fixed_title = track_info['name'][:256]
            mbid = track_info['mbid']
            toptags = track_info.get('toptags', [])
        if not mbid:
            if ';' in artist:
                # Try slicing into multiple artists and retry using the first one listed
                return self.query_lastfm(artist.split(';')[0], title)

            # Cannot continue without an MBID.
            return None
        mbid, fixed_artist, fixed_title = self.query_musicbrainz(
            mbid, fixed_artist, fixed_title)
        tags = self.extract_tags(toptags)
        return {'artist': fixed_artist, 'title': fixed_title, 'mbid': mbid,
                'tags': tags}
Example #29
0
    def __init__(self, q, start=1, count=100, wait=10, asynchronous=False, cached=True, 
                 sort=SORT_RELEVANCE, match=MATCH_ANY):

        try: q = q.encode("utf-8")
        except:
            pass

        if cached: 
            cache = "flickr"
        else:
            cache = None
        
        url  = "http://api.flickr.com/services/rest/?method="
        if q == "recent":
            url += "flickr.photos.getRecent"
        else:
            url += "flickr.photos.search"
        if isinstance(q, (list, tuple)):
            q = [quote_plus(q) for q in q]
            q = ",".join(q)
            url += "&tags=" + quote_plus(q)
            url += "&tag_mode=" + match
        else:
            url += "&text=" + quote_plus(q)
        url += "&page=" + str(start)
        url += "&per_page=" + str(count)
        url += "&sort=" + disambiguate_sort(sort)
        url += "&api_key=" + API_KEY
        
        URLAccumulator.__init__(self, url, wait, asynchronous, cache, ".xml", 1)
Example #30
0
def addDir(name,url,mode,iconimage	,showContext=False, showLiveContext=False,isItFolder=True):
#	print name
#	name=name.decode('utf-8','replace')
	h = HTMLParser.HTMLParser()
	name= h.unescape(name.decode("utf8")).encode("ascii","ignore")
	#print  name
	#print url
	#print iconimage
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
#	print iconimage
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )

	if showContext==True:
		cmd1 = "XBMC.RunPlugin(%s&linkType=%s)" % (u, "DM")
		cmd2 = "XBMC.RunPlugin(%s&linkType=%s)" % (u, "LINK")
		cmd3 = "XBMC.RunPlugin(%s&linkType=%s)" % (u, "Youtube")
		liz.addContextMenuItems([('Play Youtube video',cmd3),('Play DailyMotion video',cmd1),('Play Tune.pk video',cmd2)])
	
	if showLiveContext==True:
		cmd1 = "XBMC.RunPlugin(%s&linkType=%s)" % (u, "RTMP")
		cmd2 = "XBMC.RunPlugin(%s&linkType=%s)" % (u, "HTTP")
		liz.addContextMenuItems([('Play RTMP Steam (flash)',cmd1),('Play Http Stream (ios)',cmd2)])
	
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isItFolder)
	return ok
Example #31
0
 def getSearchURL(self, key):
     if key != None:
         url = mainUrl + '/search?search_query='+ urllib.quote_plus(key)+'&x=0&y=0'  
         return url
     else:
         return False
Example #32
0
password = os.environ.get('NEO4J_PASSWORD',"neo4j")
# url = "http://*****:*****@lewisoaten"))

count = 100
result_type = "recent"
lang = "en"
since_id = -1

while True:
    try:
        print(q)
        # Build URL.
        url = "https://api.twitter.com/1.1/search/tweets.json?q=%s&count=%s&result_type=%s&lang=%s&since_id=%s" % (q, count, result_type, lang, since_id)
        # Send GET request.
        r = requests.get(url, headers = {"accept":"application/json","Authorization":"Bearer " + TWITTER_BEARER})

        # Keep status objects.
Example #33
0
    def _get_cookie(self, netloc, ua, timeout):
        class NoRedirection(urllib2.HTTPErrorProcessor):
            def http_response(self, request, response):
                return response

        def parseJSString(s):
            try:
                offset = 1 if s[0] == '+' else 0
                val = int(
                    eval(
                        s.replace('!+[]', '1').replace('!![]', '1').replace(
                            '[]', '0').replace('(', 'str(')[offset:]))
                return val
            except:
                pass

        cookies = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(NoRedirection,
                                      urllib2.HTTPCookieProcessor(cookies))
        opener.addheaders = [('User-Agent', ua)]
        try:
            response = opener.open(netloc, timeout=int(timeout))
            result = response.read()
        except HTTPError as response:
            result = response.read()
            try:
                encoding = response.info().getheader('Content-Encoding')
            except:
                encoding = None
            if encoding == 'gzip':
                result = gzip.GzipFile(fileobj=StringIO(result)).read()

        jschl = re.compile('name="jschl_vc" value="(.+?)"/>').findall(
            result)[0]
        init = re.compile('setTimeout\(function\(\){\s*.*?.*:(.*?)};').findall(
            result)[0]
        builder = re.compile(r"challenge-form\'\);\s*(.*)a.v").findall(
            result)[0]

        if '/' in init:
            init = init.split('/')
            decryptVal = parseJSString(init[0]) / float(parseJSString(init[1]))
        else:
            decryptVal = parseJSString(init)

        lines = builder.split(';')
        for line in lines:
            if len(line) > 0 and '=' in line:
                sections = line.split('=')
                if '/' in sections[1]:
                    subsecs = sections[1].split('/')
                    line_val = parseJSString(subsecs[0]) / float(
                        parseJSString(subsecs[1]))
                else:
                    line_val = parseJSString(sections[1])
                decryptVal = float(
                    eval('%.16f' % decryptVal + sections[0][-1] +
                         '%.16f' % line_val))

        answer = float('%.10f' % decryptVal) + len(urlparse(netloc).netloc)

        query = '%scdn-cgi/l/chk_jschl?jschl_vc=%s&jschl_answer=%s' % (
            netloc, jschl, answer)

        if 'type="hidden" name="pass"' in result:
            passval = re.findall('name="pass" value="(.*?)"', result)[0]
            query = '%scdn-cgi/l/chk_jschl?pass=%s&jschl_vc=%s&jschl_answer=%s' % (
                netloc, quote_plus(passval), jschl, answer)
            time.sleep(6)

        opener.addheaders = [
            ('User-Agent', ua), ('Referer', netloc),
            ('Accept',
             'text/html, application/xhtml+xml, application/xml, */*'),
            ('Accept-Encoding', 'gzip, deflate')
        ]

        response = opener.open(query)
        response.close()

        cookie = '; '.join(['%s=%s' % (i.name, i.value) for i in cookies])
        if 'cf_clearance' in cookie: self.cookie = cookie
Example #34
0
def urlencode(txt):
    """Url encode a path."""
    if isinstance(txt, unicode):
        txt = txt.encode('utf-8')
    return urllib.quote_plus(txt)
 def sources(self, url, hostDict, hostprDict):
     try:
         sources = []
         if url == None:
             return sources
         if not str(url).startswith('http'):
             data = urlparse.parse_qs(url)
             data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
             title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
             if 'season' in data:
                 season = data['season']
             if 'episode' in data:
                 episode = data['episode']
             year = data['year']
             r = client.request(self.base_link, output='extended', timeout='10')
             cookie = r[4];
             headers = r[3];
             result = r[0]
             headers['Cookie'] = cookie
             query = urlparse.urljoin(self.base_link,
                                      self.search_link % urllib.quote_plus(cleantitle.getsearch(title)))
             r = client.request(query, headers=headers, XHR=True)
             r = json.loads(r)['content']
             r = zip(client.parseDOM(r, 'a', ret='href'), client.parseDOM(r, 'a'))
             if 'tvshowtitle' in data:
                 cltitle = cleantitle.get(title + 'season' + season)
                 cltitle2 = cleantitle.get(title + 'season%02d' % int(season))
                 r = [i for i in r if cltitle == cleantitle.get(i[1]) or cltitle2 == cleantitle.get(i[1])]
                 vurl = '%s%s-episode-%s' % (self.base_link, str(r[0][0]).replace('/info', ''), episode)
                 vurl2 = None
             else:
                 cltitle = cleantitle.getsearch(title)
                 cltitle2 = cleantitle.getsearch('%s (%s)' % (title, year))
                 r = [i for i in r if
                      cltitle2 == cleantitle.getsearch(i[1]) or cltitle == cleantitle.getsearch(i[1])]
                 vurl = '%s%s-episode-0' % (self.base_link, str(r[0][0]).replace('/info', ''))
                 vurl2 = '%s%s-episode-1' % (self.base_link, str(r[0][0]).replace('/info', ''))
             r = client.request(vurl, headers=headers)
             headers['Referer'] = vurl
             slinks = client.parseDOM(r, 'div', attrs={'class': 'anime_muti_link'})
             slinks = client.parseDOM(slinks, 'li', ret='data-video')
             if len(slinks) == 0 and not vurl2 == None:
                 r = client.request(vurl2, headers=headers)
                 headers['Referer'] = vurl2
                 slinks = client.parseDOM(r, 'div', attrs={'class': 'anime_muti_link'})
                 slinks = client.parseDOM(slinks, 'li', ret='data-video')
             for slink in slinks:
                 try:
                     if 'vidnode.net/streaming.php' in slink:
                         r = client.request('https:%s' % slink, headers=headers)
                         clinks = re.findall(r'sources:\[(.*?)\]', r)[0]
                         clinks = re.findall(r'file:\s*\'(http[^\']+)\',label:\s*\'(\d+)', clinks)
                         for clink in clinks:
                             q = source_utils.label_to_quality(clink[1])
                             sources.append(
                                 {'source': 'cdn', 'quality': q, 'language': 'en', 'url': clink[0], 'direct': True,
                                  'debridonly': False})
                     else:
                         quality = source_utils.check_url(slink)
                         valid, hoster = source_utils.is_host_valid(slink, hostDict)
                         if valid:
                             sources.append({'source': hoster, 'quality': quality, 'language': 'en', 'url': slink,
                                             'direct': False, 'debridonly': False})
                 except:
                     pass
         return sources
     except:
         return sources
Example #36
0
    def test_completion_sockets_and_messages(self):
        t, socket = self.create_connections()
        self.socket = socket

        try:
            # now that we have the connections all set up, check the code completion messages.
            msg = quote_plus('math')
            send(socket, '@@IMPORTS:%sEND@@' % msg)  # math completions
            completions = self.read_msg()
            # print_ unquote_plus(completions)

            # math is a builtin and because of that, it starts with None as a file
            start = '@@COMPLETIONS(None,(__doc__,'
            start_2 = '@@COMPLETIONS(None,(__name__,'
            if ('/math.so,' in completions
                    or '/math.cpython-33m.so,' in completions
                    or '/math.cpython-34m.so,' in completions
                    or 'math.cpython-35m' in completions
                    or 'math.cpython-36m' in completions
                    or 'math.cpython-37m' in completions
                    or 'math.cpython-38' in completions):
                return
            self.assertTrue(
                completions.startswith(start)
                or completions.startswith(start_2),
                '%s DOESNT START WITH %s' % (completions, (start, start_2)))

            self.assertTrue('@@COMPLETIONS' in completions)
            self.assertTrue('END@@' in completions)

            # now, test i
            msg = quote_plus('%s.list' % BUILTIN_MOD)
            send(socket, "@@IMPORTS:%s\nEND@@" % msg)
            found = self.read_msg()
            self.assertTrue('sort' in found,
                            'Could not find sort in: %s' % (found, ))

            # now, test search
            msg = quote_plus('inspect.ismodule')
            send(socket, '@@SEARCH%sEND@@' % msg)  # math completions
            found = self.read_msg()
            self.assertTrue('inspect.py' in found)
            for i in range(33, 100):
                if str(i) in found:
                    break
            else:
                self.fail('Could not find the ismodule line in %s' % (found, ))

            # now, test search
            msg = quote_plus('inspect.CO_NEWLOCALS')
            send(socket, '@@SEARCH%sEND@@' % msg)  # math completions
            found = self.read_msg()
            self.assertTrue('inspect.py' in found)
            self.assertTrue('CO_NEWLOCALS' in found)

            # now, test search
            msg = quote_plus('inspect.BlockFinder.tokeneater')
            send(socket, '@@SEARCH%sEND@@' % msg)
            found = self.read_msg()
            self.assertTrue('inspect.py' in found)
#            self.assertTrue('CO_NEWLOCALS' in found)

# reload modules test
#        send(socket, '@@RELOAD_MODULES_END@@')
#        ok = self.read_msg()
#        self.assertEqual('@@MSG_OK_END@@' , ok)
#        this test is not executed because it breaks our current enviroment.

        finally:
            try:
                sys.stdout.write('succedded...sending kill msg\n')
                self.send_kill_msg(socket)

                #                while not hasattr(t, 'ended'):
                #                    pass #wait until it receives the message and quits.

                socket.close()
                self.socket.close()
            except:
                pass
def append_headers(headers):
    return '|%s' % '&'.join(['%s=%s' % (key, urllib.quote_plus(headers[key])) for key in headers])
Example #38
0
def request(query, params):
    params['url'] = search_url.format(query=quote_plus(query),
                                      page=params['pageno'])

    return params
Example #39
0
def videos(url=common.args.url):
    data = common.getURL(url)
    tree=BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
    cats=tree.findAll(attrs={'class' : re.compile('(.+?)videoCollectionModule(.+?)')})
    for cat in cats:
        catname = cat.find('div',attrs={'class' : 'twocolumnheader'}).find('h3').string.title()
        if catname == common.args.name:
            episodes = cat.findAll(attrs={'class' : 'fullgallery'})
            if len(episodes) > 0:
                for video in episodes:
                    url = video.find('a')['href']
                    thumb = video.find('img')['src']
                    name = video.find('img')['alt']
                    description = video.contents[8].strip() 
                    seasonepisode = video.contents[6].strip().split('|')
                    season = int(seasonepisode[0].replace('Season','').strip())
                    episode = int(seasonepisode[1].replace('Episode','').strip())
                    displayname = '%sx%s - %s' % (str(season),str(episode),name)
                    u = sys.argv[0]
                    u += '?url="'+urllib.quote_plus(url)+'"'
                    u += '&mode="abcfamily"'
                    u += '&sitemode="play"'
                    infoLabels={ "Title":name,
                                 "Season":season,
                                 "Episode":episode,
                                 "Plot":description
                                 #"premiered":airDate,
                                 #"Duration":duration,
                                 #"TVShowTitle":tvshow
                                 }
                    common.addVideo(u,displayname,thumb,infoLabels=infoLabels)
            else:
                videos = cat.findAll(attrs={'class' : 'shortgallery'})
                for video in videos:
                    url = BASE + video.find('a')['href']
                    try:
                        thumb = video.find('img')['src']
                    except:
                        try:
                            thumb = video.find('image')['src']
                        except:
                            print 'no thumb'
                            thumb = ''
                    name = video.find(attrs={'class' : 'shortvideoTitle'}).find('a').string
                    if name == None:
                        name = video.find(attrs={'class' : 'shortvideoTitle'}).find('abbr')['title']
                    description = video.find(attrs={'class' : 'shortvideoDesc'}).string.strip()
                    try:
                        seasonepisode = video.find(attrs={'class' : 'videoSeasonInfo'}).string.strip().split('|')
                        season = int(seasonepisode[0].replace('Season','').strip())
                        episode = int(seasonepisode[1].replace('Episode','').strip())
                        displayname = '%sx%s - %s' % (str(season),str(episode),name)
                    except:
                        season = 0
                        episode = 0
                        displayname = name
                    u = sys.argv[0]
                    u += '?url="'+urllib.quote_plus(url)+'"'
                    u += '&mode="abcfamily"'
                    u += '&sitemode="play"'
                    infoLabels={ "Title":name,
                                 "Season":season,
                                 "Episode":episode,
                                 "Plot":description
                                 #"premiered":airDate,
                                 #"Duration":duration,
                                 #"TVShowTitle":tvshow
                                 }
                    common.addVideo(u,displayname,thumb,infoLabels=infoLabels)
    common.setView('episodes')
Example #40
0
 def add(self, service, name, category, title, iconimage, url, desc, rating, folder = True, isPlayable = True,strona='', kategoria=''):
     u=sys.argv[0] + "?service=" + service + "&name=" + name + "&category=" + category + "&title=" + title + "&url=" + urllib.quote_plus(url) + "&icon=" + urllib.quote_plus(iconimage)+ "&strona=" + urllib.quote_plus(strona)+ "&kategoria=" + urllib.quote_plus(kategoria)
     #log.info(str(u))
     if name == 'main-menu' or name == 'categories-menu':
         title = category
     if iconimage == '':
         iconimage = "DefaultVideo.png"
     liz=xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
     if isPlayable:
         liz.setProperty("IsPlayable", "true")
     liz.setInfo( type="Video", infoLabels={ "Title": title } )
     xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=folder)
 def get_html_from_uid(self, uid):
     url = urlparse.urljoin(
         self._search_url, self._detail_page
     ) + '?ApplicationReferenceNumber=' + urllib.quote_plus(uid)
     return self.get_html_from_url(url)
Example #42
0
def handle_job_update(conn, event):
    job_id = event['job_id']

    jobs = execute_sql(conn, '''
        SELECT id, state, name, project_id, build_id
        FROM job
        WHERE id = %s
    ''', [job_id])

    if not jobs:
        return False

    job = jobs[0]

    project_id = job['project_id']
    build_id = job['build_id']

    projects = execute_sql(conn, '''
        SELECT id, name, type
        FROM project
        WHERE id = %s
    ''', [project_id])

    if not projects:
        return False

    project = projects[0]

    if project['type'] != 'github':
        return False

    builds = execute_sql(conn, '''
        SELECT id, build_number, restart_counter, commit_id
        FROM build
        WHERE id = %s
    ''', [build_id])

    if not builds:
        return False

    build = builds[0]

    project_name = project['name']
    job_state = job['state']
    job_name = job['name']
    commit_sha = build['commit_id']
    build_id = build['id']
    build_number = build['build_number']
    build_restartCounter = build['restart_counter']

    # determine github commit state
    state = 'success'
    if job_state in ('scheduled', 'running', 'queued'):
        state = 'pending'

    if job_state in ('failure', 'skipped', 'killed'):
        state = 'failure'

    if job_state == 'error':
        state = 'error'

    logger.info("")
    logger.info("Handle job %s", job_id)
    logger.info("Setting state to %s", state)

    token = execute_sql(conn, '''
        SELECT github_api_token FROM "user" u
        INNER JOIN collaborator co
            ON co.owner = true
            AND co.project_id = %s
            AND co.user_id = u.id
    ''', [project_id])

    if not token:
        logger.warn("No API token, not updating status")
        return False

    github_api_token = token[0]['github_api_token']

    github_status_url = execute_sql(conn, '''
        SELECT github_status_url
        FROM "commit"
        WHERE id = %s
        AND project_id = %s
    ''', [commit_sha, project_id])[0]['github_status_url']

    dashboard_url = execute_sql(conn, '''
        SELECT root_url
        FROM cluster
        WHERE name = 'master'
    ''', [])[0]['root_url']

    target_url = '%s/dashboard/#/project/%s/build/%s/%s/job/%s' % (dashboard_url,
                                                                   project_name,
                                                                   build_number,
                                                                   build_restartCounter,
                                                                   urllib.quote_plus(job_name).replace('+', '%20'))

    payload = {
        "state": state,
        "target_url": target_url,
        "description": "InfraBox",
        "context": "Job: %s" % job_name
    }

    headers = {
        "Authorization": "token " + github_api_token,
        "User-Agent": "InfraBox"
    }

    # TODO(ib-steffen): support ca bundles
    try:
        r = requests.post(github_status_url,
                          data=json.dumps(payload),
                          headers=headers,
                          timeout=10,
                          verify=False)

        if r.status_code != 201:
            logger.warn("Failed to update github status: %s", r.text)
            logger.warn(github_status_url)
        else:
            logger.info("Successfully updated github status")
    except Exception as e:
        logger.warn("Failed to update github status: %s", e)
        return False

    return True
Example #43
0
def search(item,tecleado):
    logger.info("tvalacarta.channels.api_programas search")

    item.url = item.url + urllib.quote_plus(tecleado)

    return api.get_itemlist_from_item(item,viewmode="series",channel=CHANNELNAME,context="program")
Example #44
0
def get_osm_data():
    for street in MosmanStreet.objects.all():
        url = NOM_URL.format(quote_plus(street.street_name), 'Mosman')
        response = urlopen(url)
        data = json.load(response)
        print data
Example #45
0
 def get_with_subscriber(self, queue, subscriber, project=None):
     sub_container = utils._subscriber_container(queue, project)
     headers, obj = self._client.get_object(sub_container,
                                            urllib.quote_plus(subscriber))
     return self.get(queue, obj, project)
Example #46
0
    def complete(self, message, endpoint, return_to):
        if message.getOpenIDNamespace() == consumer.OPENID2_NS:
            server_url = message.getArg(consumer.OPENID2_NS, 'op_endpoint', '')
            if server_url.startswith('https://www.google.com/a/'):
                assoc_handle = message.getArg(consumer.OPENID_NS,
                                              'assoc_handle')
                assoc = self.store.getAssociation(server_url, assoc_handle)
                if assoc:
                    # update fields
                    for attr in ['claimed_id', 'identity']:
                        value = message.getArg(consumer.OPENID2_NS, attr, '')
                        value = 'https://www.google.com/accounts/o8/user-xrds?uri=%s' % urllib.quote_plus(
                            value)
                        message.setArg(consumer.OPENID2_NS, attr, value)

                    # now, resign the message
                    message.delArg(consumer.OPENID2_NS, 'sig')
                    message.delArg(consumer.OPENID2_NS, 'signed')
                    message = assoc.signMessage(message)

        return super(GoogleAppsAwareConsumer,
                     self).complete(message, endpoint, return_to)
Example #47
0
File: allucfr.py Project: mpie/repo
    def sources(self, url, hostDict, hostprDict):
        sources = []
        try:
            if url == None:
                raise Exception()

            if not (self.api and not self.api == ''):
                raise Exception()

            data = urlparse.parse_qs(url)
            data = dict([(i, data[i][0]) if data[i] else (i, '')
                         for i in data])

            title = data['tvshowtitle'] if 'tvshowtitle' in data else data[
                'title']
            year = int(
                data['year']
            ) if 'year' in data and not data['year'] == None else None
            season = int(
                data['season']
            ) if 'season' in data and not data['season'] == None else None
            episode = int(
                data['episode']
            ) if 'episode' in data and not data['episode'] == None else None
            query = '%s S%02dE%02d' % (
                title, season,
                episode) if 'tvshowtitle' in data else '%s %d' % (title, year)

            query = re.sub('(\\\|/| -|:|;|\*|\?|"|\'|<|>|\|)', ' ', query)

            query += ' lang:%s' % self.language[0]
            query = urllib.quote_plus(query)
            url = urlparse.urljoin(self.base_link, self.search_link)

            hostDict = hostprDict + hostDict

            iterations = self.streamLimit / self.streamIncrease
            last = self.streamLimit - (iterations * self.streamIncrease)
            if not last:
                iterations = iterations - 1
                last = self.streamIncrease
            iterations = iterations + 1

            seen_urls = set()
            for type in self.types:
                searchFrom = 0
                searchCount = self.streamIncrease
                for offset in range(iterations):
                    if iterations == offset + 1: searchCount = last
                    urlNew = url % (type, self.api, query, searchCount,
                                    searchFrom)
                    searchFrom = searchFrom + self.streamIncrease

                    results = client.request(urlNew)
                    results = json.loads(results)

                    apistatus = results['status']
                    if apistatus != 'success': break

                    results = results['result']

                    added = False
                    for result in results:
                        jsonName = result['title']
                        jsonSize = result['sizeinternal']
                        jsonExtension = result['extension']
                        jsonLanguage = result['lang']
                        jsonHoster = result['hostername'].lower()
                        jsonLink = result['hosterurls'][0]['url']

                        if jsonLink in seen_urls: continue
                        seen_urls.add(jsonLink)

                        if not jsonHoster in hostDict: continue

                        if not self.extensionValid(jsonExtension): continue

                        quality, info = source_utils.get_release_quality(
                            jsonName)
                        info.append(self.formatSize(jsonSize))
                        info.append(jsonName)
                        info = '|'.join(info)

                        sources.append({
                            'source': jsonHoster,
                            'quality': quality,
                            'language': jsonLanguage,
                            'url': jsonLink,
                            'info': info,
                            'direct': False,
                            'debridonly': False
                        })
                        added = True

                    if not added:
                        break

            return sources
        except:
            return sources
Example #48
0
    def GET(self):
        if not 'user' in session or session.user is None:
            f = register_form()
            return render.login(f)

        i = web.input(show_all=0, q="")

        what = "id, filename, format, description, hash, total_functions,"
        what += "analysis_date, clustered"
        where = "1 = 1"
        order = "id desc"

        q = ""
        i.q = i.q.strip(" ").replace("\n", "")
        if i.q != "":
            q = i.q
            if seems_query(q):
                fields = [
                    "id", "filename", "format", "description", "hash",
                    "total_functions", "analysis_date", "clustered"
                ]

                try:
                    query = q2w(fields, i.q)
                except:
                    return render.error(sys.exc_info()[1])
            else:
                query = "hash = %s or filename like %s or description like %s"
                i.q = i.q.replace("'", "")
                rq = repr(str(i.q))
                rq_like = repr("%" + str(i.q) + "%")
                query %= (rq, rq_like, rq_like)

            if query.strip(" ") != "":
                where += " and %s" % query

        db = open_db()
        sql = "select count(*) total from samples"
        if q != "":
            sql += " where %s" % query
        ret = db.query(sql)
        total = 0
        for row in ret:
            total = row["total"]

        limit = 15
        if i.show_all == "1":
            limit = int(total)

        ret = db.select("samples", what=what, where=where, order=order, \
                                   limit=limit)
        i = 0
        results = []
        for row in ret:
            row["filename"] = os.path.basename(row["filename"])
            if row["filename"] == row["hash"]:
                row["filename"] = "<Same as SHA1 hash>"
            results.append(row)

            i += 1
            if i > limit:
                break

        do_show_all = int(limit == int(total))
        return render.samples(results, total, do_show_all, q, quote_plus(q))
Example #49
0
def progListUgc(name, url, cat, filtrs, page, listpage):
    fltrCategory = fetchID(UGC_LIST, name)
    if page == None: page = '1'
    p_url = "http://list.letv.com/apin/chandata.json?c=%s&d=2&md=&p=%s%s"

    if (listpage == None):
        link = getHttpData(url)
        listpage = re.compile('<ul class="label_list.+?>(.+?)</ul>').findall(
            link)[0]
        listpage += re.compile(
            '<div class="sort_navy.+?">(.+?)</div>').findall(link)[0].replace(
                'li', 'lo')
        cat = updateListSEL(name, url, cat, filtrs, 0, listpage)
    p_url = p_url % (fltrCategory, page, filtrs)

    # Fetch & build video titles list for user selection, highlight user selected filter
    li = xbmcgui.ListItem(name + '(第' + str(page) + '页)【' + cat + '】(按此选择)')
    u = sys.argv[0] + "?mode=9&name=" + urllib.quote_plus(
        name) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
            cat) + "&filtrs=" + urllib.quote_plus(
                filtrs) + "&page=1" + "&listpage=" + urllib.quote_plus(
                    listpage)
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    link = getHttpData(p_url)
    if link == None: return

    playlist = xbmc.PlayList(0)  # use Music playlist for temporary storage
    playlist.clear()

    # fetch and build the video series episode list
    content = simplejson.loads(link)
    vlist = content['data_list']
    totalItems = len(vlist)
    for i in range(0, totalItems):
        vid = str(vlist[i]['vid'])
        v_url = 'http://www.letv.com/ptv/vplay/%s.html' % vid
        p_title = vlist[i]['name'].encode('utf-8')

        try:
            p_thumb = vlist[i]['images']['150*200']
        except KeyError:
            p_thumb = vlist[i]['images']['160*120']
        except:
            pass

        p_list = p_name = str(i + 1) + '. ' + p_title + ' '
        p_artist = vlist[i]['actor']
        if ((p_artist != None) and len(p_artist)):
            p_list += '[COLOR FFFF00FF]['
            for actor in p_artist:
                p_list += actor.encode('utf-8') + ' '
            p_list = p_list[:-1] + '][/COLOR]'

        p_dx = int(vlist[i]['duration'])
        if (p_dx != None):
            p_duration = "[%02d:%02d]" % (int(p_dx / 60), (p_dx % 60))
            p_list += '[COLOR FFFFFF00]' + p_duration + '[/COLOR]'

        p_album = vlist[i]['albumName']
        if (p_album != None):
            p_album = p_album.encode('utf-8')
            p_list += '[COLOR FF00FFFF][' + p_album + '][/COLOR]'

        li = xbmcgui.ListItem(p_list, iconImage='', thumbnailImage=p_thumb)
        # li.setInfo(type = "Video", infoLabels = {"Title":p_list, "Artist":p_artist})
        u = sys.argv[0] + "?mode=20" + "&name=" + urllib.quote_plus(
            p_list) + "&url=" + urllib.quote_plus(
                v_url) + "&thumb=" + urllib.quote_plus(p_thumb)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, False, totalItems)
        playlist.add(v_url, li)

    # Fetch and build page selection menu
    p_itemCount = content['data_count']
    p_pageSize = 30
    p_pageTotal = (p_itemCount + 29) / p_pageSize
    p_pageMid = int(p_pageTotal / 2)

    p_pageNum = int(page)
    if (p_pageNum <= p_pageMid):
        p_pageEnd = min(8, p_pageTotal)
        pages = range(0, p_pageEnd)
        p_pageFromEnd = max((p_pageTotal - 2), (p_pageEnd + 1))
    else:
        pages = range(2)
        p_pageFromEnd = max((p_pageTotal - 8), 2)
    for x in range(p_pageFromEnd, p_pageTotal):
        pages.append(x)

    for num in pages:
        page = num + 1
        if (page) != p_pageNum:
            li = xbmcgui.ListItem("... 第" + str(page) + "页")
            u = sys.argv[0] + "?mode=8" + "&name=" + urllib.quote_plus(
                name
            ) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
                cat) + "&filtrs=" + urllib.quote_plus(filtrs) + "&page=" + str(
                    page) + "&listpage=" + urllib.quote_plus(listpage)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Example #50
0
def gnss_assist_data_valid(name,
                           force=False,
                           valid_mins=-1,
                           expire_mins=180,
                           keep_cache=False,
                           temp_storage="ram"):
    """
    Update GNSS assist data if no longer valid according to specified thresholds.
    """

    ret = {"name": name, "result": None, "changes": {}, "comment": ""}

    # Get status of assist data
    res = salt_more.call_error_safe(__salt__["ec2x.gnss_assist_data"])
    if "error" in res:
        ret["result"] = False
        ret["comment"] = "Failed to get current state of GNSS assist data: {:}".format(
            res["error"])
        return ret

    if not force:

        # Check if assist data is valid according to thresholds
        valid = True
        if valid_mins > 0 and res["valid_mins"] >= valid_mins:
            valid = False
        if expire_mins > 0 and res["expire_mins"] <= expire_mins:
            valid = False

        if valid:
            ret["result"] = True
            ret["comment"] = "Existing GNSS assist data is still valid"
            return ret

    old = res

    # Return now if in test mode
    if __opts__["test"]:
        ret["comment"] = "GNSS assist data will be updated"
        return ret

    # Download new assist data file to cache
    cache_dir = os.path.join(__opts__["cachedir"], "extrn_files", __env__,
                             "ec2x")
    __salt__["file.mkdir"](cache_dir)

    cached_file = os.path.join(cache_dir, urllib.quote_plus(name))
    res = __salt__["cmd.run_all"]("wget -O {:} {:}".format(cached_file, name))
    if res["retcode"] != 0:
        ret["result"] = False
        ret["comment"] = "Failed to download assist data file: {:}".format(
            res["stderr"])
        return ret

    filename = None
    storage = None

    try:
        # Upload cached assist data file to device
        res = salt_more.call_error_safe(__salt__["ec2x.upload_file"],
                                        cached_file,
                                        storage=temp_storage)
        if "error" in res:
            ret["result"] = False
            ret["comment"] = "Failed to upload GNSS assist data file to EC2X module: {:}".format(
                res["error"])
            return ret

        filename = res["name"]
        storage = res["storage"]
    finally:
        # Clean up cached file
        if not keep_cache:
            os.unlink(cached_file)

    try:
        # Inject assist time
        res = salt_more.call_error_safe(__salt__["ec2x.gnss_assist_time"])
        if "error" in res:
            ret["result"] = False
            ret["comment"] = "Failed to inject GNSS assist time into GNSS engine: {:}".format(
                res["error"])
            return ret

        # Inject assist data file
        res = salt_more.call_error_safe(__salt__["ec2x.gnss_assist_data"],
                                        filename=filename,
                                        storage=storage)
        if "error" in res:
            ret["result"] = False
            ret["comment"] = "Failed to inject GNSS assist data file '{:s}' into GNSS engine: {:}".format(
                filename, res["error"])
            return ret

    finally:
        # Delete assist data file from device
        res = salt_more.call_error_safe(__salt__["ec2x.delete_file"],
                                        filename,
                                        storage=storage)
        if "error" in res and ret[
                "result"] == None:  # Do not overwrite other result if present
            ret["result"] = False
            ret["comment"] = "Failed to delete GNSS assist data file '{:s}' from EC2X module: {:}".format(
                filename, res["error"])
            return ret

    # Check again status of assist data
    res = salt_more.call_error_safe(__salt__["ec2x.gnss_assist_data"])
    if "error" in res:
        ret["result"] = False
        ret["comment"] = "Failed to get state of GNSS assist data after update: {:}".format(
            res["error"])
        return ret

    # Trigger event to notify that GNSS assist data has been updated
    __salt__["minionutil.trigger_event"](
        "system/device/ec2x/gnss/assist_data_updated")

    new = res

    ret["result"] = True
    ret["comment"] = "Successfully updated GNSS assist data"
    ret["changes"]["old"] = old
    ret["changes"]["new"] = new
    return ret
Example #51
0
def progListStar(name, url, cat, filtrs, page, listpage):
    fltrCategory = fetchID(VIDEO_LIST, name)
    if page == None: page = '1'
    p_url = "http://list.letv.com/apin/stardata.json?d=%s&p=%s%s"

    if (listpage == None):
        link = getHttpData(url)
        listpage = re.compile('<ul class="label_list.+?>(.+?)</ul>').findall(
            link)[0]
        match = re.compile('<div class="sort_navy.+?">(.+?)</div>').findall(
            link)
        if len(match):
            listpage += match[0].replace('li', 'lo')
        cat = updateListSEL(name, url, cat, filtrs, 0, listpage)
    p_url = p_url % (fltrCategory, page, filtrs)

    # Fetch & build video titles list for user selection, highlight user selected filter
    li = xbmcgui.ListItem(name + '(第' + str(page) + '页)【' + cat + '】(按此选择)')
    u = sys.argv[0] + "?mode=9&name=" + urllib.quote_plus(
        name) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
            cat) + "&filtrs=" + urllib.quote_plus(
                filtrs) + "&page=1" + "&listpage=" + urllib.quote_plus(
                    listpage)
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    link = getHttpData(p_url)
    if link == None: return

    # fetch and build the video series episode list
    content = simplejson.loads(link)
    vlist = content['data_list']
    totalItems = len(vlist)
    for i in range(0, totalItems):
        p_name = vlist[i]['name'].encode('utf-8')
        #v_url = 'http://so.letv.com/star?wd=%s&from=list' % p_name
        v_url = 'http://so.letv.com/s?wd=%s' % p_name
        p_thumb = vlist[i]['postS1']
        p_list = str(i + 1) + '. [COLOR FF00FF00]' + p_name + '[/COLOR] '

        match = vlist[i]['professional']
        p_prof = re.compile('":"(.+?)"').findall(match)
        if ((p_prof != None) and len(p_prof)):
            p_list += '[COLOR FF00FFFF]['
            for prof in p_prof:
                p_list += prof.encode('utf-8') + ' '
            p_list = p_list[:-1] + '][/COLOR] '

        p_area = vlist[i]['areaName']
        if (p_area != None):
            p_list += '[COLOR FFFFFF00][' + p_area.encode(
                'utf-8') + '][/COLOR] '

        p_birthday = vlist[i]['birthday']
        if (p_birthday != None and len(p_birthday)):
            p_list += '[COLOR FFFF00FF][' + p_birthday.encode(
                'utf-8') + '][/COLOR]'

        li = xbmcgui.ListItem(p_list, iconImage='', thumbnailImage=p_thumb)
        # li.setInfo(type = "Video", infoLabels = {"Title":p_list, "Artist":p_name})
        u = sys.argv[0] + "?mode=5" + "&name=" + urllib.quote_plus(
            p_name) + "&url=" + urllib.quote_plus(
                v_url) + "&thumb=" + urllib.quote_plus(p_thumb)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True, totalItems)

    # Fetch and build page selection menu
    p_itemCount = content['video_count']
    p_pageSize = 30
    p_pageTotal = (p_itemCount + 29) / p_pageSize
    p_pageMid = int(p_pageTotal / 2)

    p_pageNum = int(page)
    if (p_pageNum <= p_pageMid):
        p_pageEnd = min(8, p_pageTotal)
        pages = range(0, p_pageEnd)
        p_pageFromEnd = max((p_pageTotal - 2), (p_pageEnd + 1))
    else:
        pages = range(2)
        p_pageFromEnd = max((p_pageTotal - 8), 2)
    for x in range(p_pageFromEnd, p_pageTotal):
        pages.append(x)

    for num in pages:
        page = num + 1
        if (page) != p_pageNum:
            li = xbmcgui.ListItem("... 第" + str(page) + "页")
            u = sys.argv[0] + "?mode=4" + "&name=" + urllib.quote_plus(
                name
            ) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
                cat) + "&filtrs=" + urllib.quote_plus(filtrs) + "&page=" + str(
                    page) + "&listpage=" + urllib.quote_plus(listpage)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Example #52
0
def letvSearchList(name, page):
    p_url = 'http://open.api.letv.com/ms?hl=1&dt=2&ph=420001&from=pcjs&pn=%s&ps=30&wd=%s'
    p_url = p_url % (page, urllib.quote(name))
    link = getHttpData(p_url)

    li = xbmcgui.ListItem('[COLOR FFFF0000]当前搜索: 第' + page +
                          '页[/COLOR][COLOR FFFFFF00] (' + name +
                          ')[/COLOR]【[COLOR FF00FF00]' + '点此输入新搜索内容' +
                          '[/COLOR]】')
    u = sys.argv[0] + "?mode=31&name=" + urllib.quote_plus(
        name) + "&page=" + page
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    if link == None:
        li = xbmcgui.ListItem('  抱歉,没有找到[COLOR FFFF0000] ' + name +
                              ' [/COLOR]的相关视频')
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, False)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
        return

    # fetch and build the video series episode list
    content = simplejson.loads(link)
    vlist = content['data_list']
    totalItems = len(vlist)
    for i in range(0, totalItems):
        vid = str(vlist[i]['vid'])
        v_url = 'http://www.letv.com/ptv/vplay/%s.html' % vid
        p_title = vlist[i]['name'].encode('utf-8')

        try:
            p_thumb = vlist[i]['images']['150*200']
        except KeyError:
            p_thumb = vlist[i]['images']['160*120']
        except:
            pass

        p_categoryName = vlist[i]['categoryName']
        if (p_categoryName != None):
            p_list = p_name = str(
                i + 1) + '. [COLOR FF00FFFF][' + p_categoryName.encode(
                    'utf-8') + '][/COLOR] ' + p_title + ' '
        else:
            p_list = p_name = str(i + 1) + '. ' + p_title + ' '

        try:
            p_rating = float(vlist[i]['rating'])
            if (p_rating != None and p_rating > 0.01):
                p_rating = "%0.1f" % p_rating
                p_list += '[COLOR FFFF00FF][' + p_rating + '][/COLOR]'
        except:
            pass

        p_dx = int(vlist[i]['duration'])
        if (p_dx != None):
            p_duration = "[%02d:%02d]" % (int(p_dx / 60), (p_dx % 60))
            p_list += '[COLOR FFFFFF00]' + p_duration + '[/COLOR]'

        p_artists = vlist[i]['actor']
        if ((p_artists != None) and len(p_artists)):
            p_artist = ""
            p_list += '['
            for key in p_artists:
                p_artist += p_artists[key].encode('utf-8') + ' '
            p_list += p_artist[:-1] + ']'

        li = xbmcgui.ListItem(p_list, iconImage='', thumbnailImage=p_thumb)
        u = sys.argv[0] + "?mode=10" + "&name=" + urllib.quote_plus(
            p_list) + "&url=" + urllib.quote_plus(
                v_url) + "&thumb=" + urllib.quote_plus(p_thumb)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, False, totalItems)

    # Fetch and build page selection menu
    p_itemCount = content['video_count']
    p_pageSize = 30
    p_pageTotal = (p_itemCount + 29) / p_pageSize
    p_pageMid = int(p_pageTotal / 2)

    p_pageNum = int(page)
    if (p_pageNum <= p_pageMid):
        p_pageEnd = min(8, p_pageTotal)
        pages = range(0, p_pageEnd)
        p_pageFromEnd = max((p_pageTotal - 2), (p_pageEnd + 1))
    else:
        pages = range(2)
        p_pageFromEnd = max((p_pageTotal - 8), 2)
    for x in range(p_pageFromEnd, p_pageTotal):
        pages.append(x)

    for num in pages:
        page = num + 1
        if (page) != p_pageNum:
            li = xbmcgui.ListItem("... 第" + str(page) + "页")
            u = sys.argv[0] + "?mode=32" + "&name=" + urllib.quote_plus(
                name) + "&page=" + str(page)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Example #53
0
    def movieDirectory(self, items):
        if items == None or len(items) == 0: return

        isFolder = True if control.setting(
            'autoplay') == 'false' and control.setting(
                'hosts.mode') == '1' else False
        isFolder = False if control.window.getProperty(
            'PseudoTVRunning') == 'True' else isFolder

        playbackMenu = control.lang(30204).encode('utf-8') if control.setting(
            'autoplay') == 'true' else control.lang(30203).encode('utf-8')

        traktCredentials = trakt.getTraktCredentialsInfo()

        indicators = playcount.getMovieIndicators()

        cacheToDisc = False if not action == 'movieSearch' else True

        addonPoster, addonBanner = control.addonPoster(), control.addonBanner()
        addonFanart, settingFanart = control.addonFanart(), control.setting(
            'fanart')
        sysaddon = sys.argv[0]

        for i in items:
            try:
                label = '%s (%s)' % (i['title'], i['year'])
                imdb, title, year = i['imdb'], i['originaltitle'], i['year']
                sysname = urllib.quote_plus('%s (%s)' % (title, year))
                sysimage = urllib.quote_plus(i['poster'])
                systitle = urllib.quote_plus(title)

                poster, banner, fanart = i['poster'], i['banner'], i['fanart']
                if poster == '0': poster = addonPoster
                if banner == '0' and poster == '0': banner = addonBanner
                elif banner == '0': banner = poster

                meta = dict((k, v) for k, v in i.iteritems() if not v == '0')
                meta.update({
                    'trailer':
                    '%s?action=trailer&name=%s' % (sysaddon, sysname)
                })
                if i['duration'] == '0': meta.update({'duration': '120'})
                try:
                    meta.update({'duration': str(int(meta['duration']) * 60)})
                except:
                    pass
                try:
                    meta.update(
                        {'genre': cleangenre.lang(meta['genre'], self.lang)})
                except:
                    pass
                sysmeta = urllib.quote_plus(json.dumps(meta))

                url = '%s?action=play&title=%s&year=%s&imdb=%s&meta=%s&t=%s' % (
                    sysaddon, systitle, year, imdb, sysmeta, self.systime)
                sysurl = urllib.quote_plus(url)

                path = '%s?action=play&title=%s&year=%s&imdb=%s' % (
                    sysaddon, systitle, year, imdb)

                if isFolder == True:
                    url = '%s?action=sources&title=%s&year=%s&imdb=%s&meta=%s' % (
                        sysaddon, systitle, year, imdb, sysmeta)

                try:
                    overlay = int(playcount.getMovieOverlay(indicators, imdb))
                    if overlay == 7:
                        meta.update({'playcount': 1, 'overlay': 7})
                    else:
                        meta.update({'playcount': 0, 'overlay': 6})
                except:
                    pass

                cm = []

                cm.append((playbackMenu,
                           'RunPlugin(%s?action=alterSources&url=%s&meta=%s)' %
                           (sysaddon, sysurl, sysmeta)))

                if isFolder == False:
                    cm.append((control.lang(30202).encode('utf-8'),
                               'RunPlugin(%s?action=queueItem)' % sysaddon))

                if traktCredentials == True:
                    cm.append((control.lang(30208).encode(
                        'utf-8'
                    ), 'RunPlugin(%s?action=traktManager&name=%s&imdb=%s&content=movie)'
                               % (sysaddon, sysname, imdb)))

                cm.append((control.lang(30214).encode('utf-8'),
                           'RunPlugin(%s?action=trailer&name=%s)' %
                           (sysaddon, sysname)))
                cm.append(
                    (control.lang(30205).encode('utf-8'), 'Action(Info)'))
                cm.append(
                    (control.lang(30206).encode('utf-8'),
                     'RunPlugin(%s?action=moviePlaycount&imdb=%s&query=7)' %
                     (sysaddon, imdb)))
                cm.append(
                    (control.lang(30207).encode('utf-8'),
                     'RunPlugin(%s?action=moviePlaycount&imdb=%s&query=6)' %
                     (sysaddon, imdb)))
                cm.append(
                    (control.lang(30212).encode('utf-8'),
                     'RunPlugin(%s?action=addView&content=movies)' % sysaddon))

                item = control.item(label=label,
                                    iconImage=poster,
                                    thumbnailImage=poster)

                try:
                    item.setArt({'poster': poster, 'banner': banner})
                except:
                    pass

                if settingFanart == 'true' and not fanart == '0':
                    item.setProperty('Fanart_Image', fanart)
                elif not addonFanart == None:
                    item.setProperty('Fanart_Image', addonFanart)

                item.setInfo(type='Video', infoLabels=meta)
                item.setProperty('Video', 'true')
                #item.setProperty('IsPlayable', 'true')
                item.addContextMenuItems(cm, replaceItems=True)
                control.addItem(handle=int(sys.argv[1]),
                                url=url,
                                listitem=item,
                                isFolder=isFolder)
            except:
                pass

        try:
            url = items[0]['next']
            if url == '': raise Exception()
            url = '%s?action=movies&url=%s' % (sysaddon,
                                               urllib.quote_plus(url))
            addonNext = control.addonNext()
            item = control.item(label=control.lang(30213).encode('utf-8'),
                                iconImage=addonNext,
                                thumbnailImage=addonNext)
            item.addContextMenuItems([], replaceItems=True)
            if not addonFanart == None:
                item.setProperty('Fanart_Image', addonFanart)
            control.addItem(handle=int(sys.argv[1]),
                            url=url,
                            listitem=item,
                            isFolder=True)
        except:
            pass

        control.content(int(sys.argv[1]), 'movies')
        control.directory(int(sys.argv[1]), cacheToDisc=cacheToDisc)
        views.setView('movies', {'skin.confluence': 500})
Example #54
0
def progListStarVideo(name, url, page, thumb):
    if (page == None): page = '1'
    p_url = 'http://open.api.letv.com/ms?hl=1&dt=2&pn=%s&ps=30&wd=%s' % (page,
                                                                         name)

    li = xbmcgui.ListItem('【[COLOR FF00FFFF][' + name +
                          '][/COLOR] | [COLOR FFFFFF00](第' + page +
                          '页)[/COLOR]】',
                          iconImage='',
                          thumbnailImage=thumb)
    u = sys.argv[0] + "?mode=5&name=" + urllib.quote_plus(
        name) + "&url=" + urllib.quote_plus(
            url) + "&thumb=" + urllib.quote_plus(thumb)
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    link = getHttpData(p_url)
    if link == None: return

    playlist = xbmc.PlayList(0)  # use Music playlist for temporary storage
    playlist.clear()

    # fetch and build the video series episode list
    content = simplejson.loads(link)
    vlist = content['data_list']
    totalItems = len(vlist)
    for i in range(0, totalItems):
        p_title = vlist[i]['name'].encode('utf-8')

        # aid = str(vlist[i]['aid'])
        vid = str(vlist[i]['vid'])
        v_url = 'http://www.letv.com/ptv/vplay/%s.html' % vid

        try:
            p_thumb = vlist[i]['images']['150*200']
        except KeyError:
            p_thumb = vlist[i]['images']['160*120']
        except:
            p_thumb = ''

        p_name = p_list = str(i + 1) + '. ' + p_title + ' '
        p_category = vlist[i]['categoryName']
        if ((p_category != None) and len(p_category)):
            # p_cat = p_category.encode('utf-8')
            # if(p_cat != '电影' and p_cat != '电视剧'): continue
            p_list += '[COLOR FF00FFFF][' + p_category.encode(
                'utf-8') + '][/COLOR] '

        try:
            p_rating = float(vlist[i]['rating'])
            if (p_rating != None and p_rating > 0.01):
                p_rating = "%0.1f" % p_rating
                p_list += '[COLOR FFFF00FF][' + p_rating + '][/COLOR]'
        except:
            pass

        p_dx = int(vlist[i]['duration'])
        if ((p_dx != None) and (p_dx > 0)):
            p_duration = "[%02d:%02d]" % (int(p_dx / 60), (p_dx % 60))
            p_list += '[COLOR FFFFFF00]' + p_duration + '[/COLOR]'

        li = xbmcgui.ListItem(p_list, iconImage='', thumbnailImage=p_thumb)
        # li.setInfo(type = "Video", infoLabels = {"Title":p_list, "Artist":p_name})
        u = sys.argv[0] + "?mode=20" + "&name=" + urllib.quote_plus(
            p_name) + "&url=" + urllib.quote_plus(
                v_url) + "&thumb=" + urllib.quote_plus(p_thumb)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True, totalItems)
        playlist.add(v_url, li)

    # Fetch and build page selection menu
    p_itemCount = content['data_count']
    p_pageSize = 30
    p_pageTotal = (p_itemCount + 29) / p_pageSize
    p_pageMid = int(p_pageTotal / 2)

    p_pageNum = int(page)
    if (p_pageNum <= p_pageMid):
        p_pageEnd = min(8, p_pageTotal)
        pages = range(0, p_pageEnd)
        p_pageFromEnd = max((p_pageTotal - 2), (p_pageEnd + 1))
    else:
        pages = range(2)
        p_pageFromEnd = max((p_pageTotal - 8), 2)
    for x in range(p_pageFromEnd, p_pageTotal):
        pages.append(x)

    for num in pages:
        page = num + 1
        if (page) != p_pageNum:
            li = xbmcgui.ListItem("... 第" + str(page) + "页")
            u = sys.argv[0] + "?mode=5" + "&name=" + urllib.quote_plus(
                name) + "&url=" + urllib.quote_plus(url) + "&page=" + str(
                    page) + "&thumb=" + urllib.quote_plus(thumb)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Example #55
0
 def get_html_from_uid(self, uid):
     url = self._applic_url + urllib.quote_plus(uid)
     return self.get_html_from_url(url)
Example #56
0
def progListMovie(name, url, cat, filtrs, page, listpage):
    fltrCategory = fetchID(VIDEO_LIST, name)
    if page == None: page = '1'
    p_url = "http://list.letv.com/apin/chandata.json?c=%s&d=2&md=&p=%s%s"

    if (listpage == None):
        link = getHttpData(url)
        listpage = re.compile('<ul class="label_list.+?>(.+?)</ul>').findall(
            link)[0]
        match = re.compile('<div class="sort_navy.+?">(.+?)</div>').findall(
            link)
        if len(match):
            listpage += match[0].replace('li', 'lo')
        cat = updateListSEL(name, url, cat, filtrs, 0, listpage)
    p_url = p_url % (fltrCategory, page, filtrs)

    # Fetch & build video titles list for user selection, highlight user selected filtrs
    li = xbmcgui.ListItem(name + '(第' + str(page) + '页)【' + cat + '】(按此选择)')
    u = sys.argv[0] + "?mode=9&name=" + urllib.quote_plus(
        name) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
            cat) + "&filtrs=" + urllib.quote_plus(
                filtrs) + "&page=1" + "&listpage=" + urllib.quote_plus(
                    listpage)
    xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    link = getHttpData(p_url)
    if link == None: return

    # Movie, Video, Series, Variety & Music titles need different routines
    if ((name == '电视剧') or (name == '动漫')):
        isDir = True
        mode = '2'
    elif ((name == '电影') or (name == '综艺')):
        isDir = False
        mode = '10'

    # fetch and build the video series episode list
    content = simplejson.loads(link)
    vlist = content['data_list']
    totalItems = len(vlist)
    for i in range(0, totalItems):
        p_name = vlist[i]['name'].encode('utf-8')
        if ((name == '电视剧') or (name == '动漫')):
            aid = str(vlist[i]['aid'])
            if (name == '电视剧'): v_url = 'http://www.letv.com/tv/%s.html' % aid
            else: v_url = 'http://www.letv.com/comic/%s.html' % aid
        else:
            if (name == '综艺'):
                vid = str(vlist[i]['vid'])
                p_name = p_name.split(":")[0]
            else:  # '电影'
                vid = str(vlist[i]['vids'].split(',')[0])
            v_url = 'http://www.letv.com/ptv/vplay/%s.html' % vid

        try:
            p_thumb = vlist[i]['images']['150*200']
        except KeyError:
            p_thumb = vlist[i]['images']['160*120']
        except:
            p_thumb = ''

        p_title = p_name
        p_list = str(i + 1) + '. ' + p_title + ' '
        try:
            p_rating = float(vlist[i]['rating'])
            if (p_rating != None and p_rating > 0.01):
                p_rating = "%0.1f" % p_rating
                p_list += '[COLOR FFFF00FF][' + p_rating + '][/COLOR]'
        except:
            pass

        if ((name == '电影') or (name == '动漫')):
            p_lang = vlist[i]['lgName']
            if (p_lang != None):
                p_list += '[COLOR FF00FFFF][' + p_lang.encode(
                    'utf-8') + '][/COLOR]'
        else:
            p_area = vlist[i]['areaName']
            if (p_area != None):
                p_list += '[COLOR FF00FFFF][' + p_area.encode(
                    'utf-8') + '][/COLOR]'

        p_dx = int(vlist[i]['duration'])
        if ((p_dx != None) and (p_dx > 0)):
            p_duration = "[%02d:%02d]" % (int(p_dx / 60), (p_dx % 60))
            p_list += '[COLOR FFFFFF00]' + p_duration + '[/COLOR]'

        p_artists = vlist[i]['starring']
        if ((p_artists != None) and len(p_artists)):
            p_artist = ""
            p_list += '['
            for key in p_artists:
                p_artist += p_artists[key].encode('utf-8') + ' '
            p_list += p_artist[:-1] + ']'
        else:
            p_subcategory = vlist[i]['subCategoryName']
            if ((p_subcategory != None)):
                p_list += '[' + p_subcategory.encode('utf-8') + ']'

        li = xbmcgui.ListItem(p_list, iconImage='', thumbnailImage=p_thumb)
        # li.setInfo(type = "Video", infoLabels = {"Title":p_list, "Artist":p_artist})
        u = sys.argv[0] + "?mode=" + mode + "&name=" + urllib.quote_plus(
            p_name) + "&url=" + urllib.quote_plus(
                v_url) + "&thumb=" + urllib.quote_plus(p_thumb)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, isDir, totalItems)

    # Fetch and build page selection menu
    p_itemCount = content['data_count']
    p_pageSize = 30
    p_pageTotal = (p_itemCount + 29) / p_pageSize
    p_pageMid = int(p_pageTotal / 2)

    p_pageNum = int(page)
    if (p_pageNum <= p_pageMid):
        p_pageEnd = min(8, p_pageTotal)
        pages = range(0, p_pageEnd)
        p_pageFromEnd = max((p_pageTotal - 2), (p_pageEnd + 1))
    else:
        pages = range(2)
        p_pageFromEnd = max((p_pageTotal - 8), 2)
    for x in range(p_pageFromEnd, p_pageTotal):
        pages.append(x)

    for num in pages:
        page = num + 1
        if (page) != p_pageNum:
            li = xbmcgui.ListItem("... 第" + str(page) + "页")
            u = sys.argv[0] + "?mode=1" + "&name=" + urllib.quote_plus(
                name
            ) + "&url=" + urllib.quote_plus(url) + "&cat=" + urllib.quote_plus(
                cat) + "&filtrs=" + urllib.quote_plus(filtrs) + "&page=" + str(
                    page) + "&listpage=" + urllib.quote_plus(listpage)
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), u, li, True)

    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Example #57
0
def add_directory(name,
                  mode='',
                  sitemode='',
                  directory_url='',
                  thumb=None,
                  fanart=None,
                  description=None,
                  aired='',
                  genre='',
                  count=0):
    if fanart is None:
        if args.__dict__.has_key('fanart'):
            fanart = args.fanart
        else:
            fanart = PLUGINFANART
    if thumb is None:
        if args.__dict__.has_key('poster'):
            thumb = args.poster
        elif args.__dict__.has_key('thumb'):
            thumb = args.thumb
        else:
            thumb = ''
    if args.__dict__.has_key('name'):
        showname = args.name
    else:
        showname = ''
    if description is None:
        if args.__dict__.has_key('tvdb_id'):
            description = get_plot_by_tvdbid(args.tvdb_id)
        else:
            network = get_network(mode)
            description = network.DESCRIPTION
    infoLabels = {
        'title': name,
        'tvshowtitle': showname,
        'genre': genre,
        'premiered': aired,
        'plot': description,
        'count': count
    }
    u = sys.argv[0]
    u += '?url="' + urllib.quote_plus(directory_url) + '"'
    u += '&mode="' + mode + '"'
    u += '&sitemode="' + sitemode + '"'
    u += '&thumb="' + urllib.quote_plus(thumb) + '"'
    u += '&fanart="' + urllib.quote_plus(fanart) + '"'
    u += '&name="' + urllib.quote_plus(name) + '"'
    if args.__dict__.has_key('tvdb_id'):
        u += '&tvdb_id="' + urllib.quote_plus(args.tvdb_id) + '"'
    item = xbmcgui.ListItem(name, iconImage=thumb, thumbnailImage=thumb)
    item.setProperty('fanart_image', fanart)
    item.setInfo(type='Video', infoLabels=infoLabels)
    contextmenu = []
    refresh_u = sys.argv[0] + '?url="<join>"' + sys.argv[
        0] + '?url="' + '&mode=_contextmenu' + '&sitemode=refresh_db'
    contextmenu.append(
        (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39021)),
         'XBMC.RunPlugin(%s)' % refresh_u))
    item.addContextMenuItems(contextmenu)
    xbmcplugin.addDirectoryItem(pluginHandle,
                                url=u,
                                listitem=item,
                                isFolder=True)
Example #58
0
 def get_storage_url(self, remote_name):
     return 'sauce-storage:' + urllib.quote_plus(remote_name)
Example #59
0
def add_show(series_title='',
             mode='',
             sitemode='',
             url='',
             favor=0,
             hide=0,
             masterList=False,
             showdata=None):
    infoLabels = {}
    tvdbfanart = None
    tvdbbanner = None
    tvdbposter = None
    tvdb_id = None
    thumb = ''
    fanart = ''
    prefixplot = ''
    actors2 = []
    if showdata is None:
        showdata = get_show_data(series_title, mode, sitemode, url)
    series_title, mode, sitemode, url, tvdb_id, imdb_id, tvdbbanner, tvdbposter, tvdbfanart, first_aired, date, year, actors, genres, network, plot, runtime, rating, airs_dayofweek, airs_time, status, has_full_episodes, favor, hide, tvdb_series_title = showdata
    network_module = get_network(mode)
    if not network_module:
        return

    network_name = network_module.NAME
    network_description = network_module.DESCRIPTION
    if tvdbfanart is not None:
        fanart = tvdbfanart
    else:
        if args.__dict__.has_key('fanart'):
            fanart = args.fanart
        else:
            fanart = None
    if tvdbbanner is not None:
        thumb = tvdbbanner
    elif tvdbposter is not None:
        thumb = tvdbposter
    else:
        thumb = os.path.join(IMAGEPATH, mode + '.png')
    orig_series_title = series_title
    if tvdb_series_title is not None:
        series_title = smart_utf8(tvdb_series_title)
    infoLabels['title'] = series_title
    infoLabels['tvShowtitle'] = series_title

    if network_name.endswith(', The'):
        station = 'The ' + network_name.replace(', The', '')
    else:
        station = network_name
    if network is not None:
        if station == network:
            prefixplot += smart_utf8(
                xbmcaddon.Addon(
                    id=ADDONID).getLocalizedString(39013)) + station + '\n'
        else:
            prefixplot += smart_utf8(
                xbmcaddon.Addon(
                    id=ADDONID).getLocalizedString(39012)) + network + '\n'
            prefixplot += smart_utf8(
                xbmcaddon.Addon(
                    id=ADDONID).getLocalizedString(39013)) + station + '\n'
    else:
        prefixplot += smart_utf8(
            xbmcaddon.Addon(
                id=ADDONID).getLocalizedString(39013)) + station + '\n'
    if (airs_dayofweek is not None) and (airs_time is not None):
        prefixplot += smart_utf8(
            xbmcaddon.Addon(id=ADDONID).getLocalizedString(
                39014)) + airs_dayofweek + '@' + airs_time + '\n'
    elif (airs_dayofweek is not None) and (airs_time is None):
        prefixplot += smart_utf8(
            xbmcaddon.Addon(
                id=ADDONID).getLocalizedString(39014)) + airs_dayofweek + '\n'
    elif (airs_dayofweek is None) and (airs_time is not None):
        prefixplot += smart_utf8(
            xbmcaddon.Addon(
                id=ADDONID).getLocalizedString(39014)) + airs_time + '\n'
    else:
        pass
    if status is not None:
        prefixplot += smart_utf8(
            xbmcaddon.Addon(
                id=ADDONID).getLocalizedString(39015)) + status + '\n'
    if prefixplot is not None:
        prefixplot += '\n'
    if plot is not None:
        infoLabels['plot'] = smart_utf8(prefixplot) + smart_utf8(
            replace_signs(plot))
    else:
        infoLabels['plot'] = smart_utf8(prefixplot)
    if date is not None:
        infoLabels['date'] = smart_utf8(date)
    if first_aired is not None:
        infoLabels['aired'] = smart_utf8(first_aired)
    if year is not None:
        infoLabels['year'] = smart_utf8(year)
    if actors is not None:
        actors = actors.strip('|').split('|')
        if actors[0] is not '':
            for actor in actors:
                actors2.append(smart_utf8(actor))
            infoLabels['cast'] = actors2
    if genres is not None:
        infoLabels['genre'] = smart_utf8(genres.replace('|', ',').strip(','))
    if network is not None:
        infoLabels['studio'] = smart_utf8(network)
    if runtime is not None:
        infoLabels['duration'] = smart_utf8(runtime)
    if rating is not None:
        infoLabels['rating'] = smart_utf8(rating)
    name = smart_utf8(replace_signs(series_title))
    series_title = smart_utf8(replace_signs(series_title))
    u = sys.argv[0]
    u += '?url="' + urllib.quote_plus(url) + '"'
    u += '&mode="' + mode + '"'
    u += '&sitemode="' + sitemode + '"'
    u += '&thumb="' + urllib.quote_plus(thumb) + '"'
    if tvdb_id is not None:
        u += '&tvdb_id="' + urllib.quote_plus(tvdb_id) + '"'
    if PLUGINFANART is not fanart and fanart is not None:
        u += '&fanart="' + urllib.quote_plus(fanart) + '"'
    if tvdbposter is not None:
        u += '&poster="' + urllib.quote_plus(tvdbposter) + '"'
    u += '&name="' + urllib.quote_plus(series_title) + '"'
    contextmenu = []
    refresh_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
        orig_series_title, mode, sitemode, url
    ])) + '&mode=_contextmenu' + '&sitemode=refresh_show'
    contextmenu.append(
        (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39008)),
         'XBMC.RunPlugin(%s)' % refresh_u))
    if favor is 1:
        fav_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
            series_title, mode, sitemode, url
        ])) + '&mode=_contextmenu' + '&sitemode=unfavor_show'
        contextmenu.append(
            (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39006)),
             'XBMC.RunPlugin(%s)' % fav_u))
    else:
        fav_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
            series_title, mode, sitemode, url
        ])) + '&mode=_contextmenu' + '&sitemode=favor_show'
        contextmenu.append(
            (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39007)),
             'XBMC.RunPlugin(%s)' % fav_u))
    if hide is 1:
        hide_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
            series_title, mode, sitemode, url
        ])) + '&mode=_contextmenu' + '&sitemode=unhide_show'
        contextmenu.append(
            (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39009)),
             'XBMC.RunPlugin(%s)' % hide_u))
    else:
        hide_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
            series_title, mode, sitemode, url
        ])) + '&mode=_contextmenu' + '&sitemode=hide_show'
        contextmenu.append(
            (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39010)),
             'XBMC.RunPlugin(%s)' % hide_u))
    delete_u = sys.argv[0] + '?url="' + urllib.quote_plus('<join>'.join([
        series_title, mode, sitemode, url
    ])) + '&mode=_contextmenu' + '&sitemode=delete_show'
    contextmenu.append(
        (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39011)),
         'XBMC.RunPlugin(%s)' % delete_u))
    if masterList:
        displayname = name + ' on ' + network_name
    else:
        displayname = name
    item = xbmcgui.ListItem(displayname, iconImage=thumb, thumbnailImage=thumb)
    item.addContextMenuItems(contextmenu)
    item.setProperty('fanart_image', fanart)
    item.setInfo(type='Video', infoLabels=infoLabels)
    xbmcplugin.addDirectoryItem(pluginHandle,
                                url=u,
                                listitem=item,
                                isFolder=True)
Example #60
0
def add_video(video_url,
              displayname,
              thumb=None,
              fanart=None,
              infoLabels=False,
              HD=False,
              quality_mode=False):
    displayname = smart_utf8(replace_signs(smart_unicode(displayname)))
    if fanart is None:
        if args.__dict__.has_key('fanart'):
            fanart = args.fanart
        else:
            fanart = PLUGINFANART
    if thumb is None:
        if args.__dict__.has_key('thumb'):
            thumb = args.thumb
        else:
            thumb = ''
    item = xbmcgui.ListItem(displayname, iconImage=thumb, thumbnailImage=thumb)
    item.setInfo(type='Video', infoLabels=infoLabels)
    try:
        if 'durationinseconds' in infoLabels.keys():
            duration = infoLabels['durationinseconds']
        else:
            duration = 0
        if HD is True:
            item.addStreamInfo(
                'video', {
                    'codec': 'h264',
                    'width': 1280,
                    'height': 720,
                    'duration': duration
                })
        else:
            item.addStreamInfo('video', {
                'codec': 'h264',
                'width': 720,
                'height': 400,
                'duration': duration
            })
        item.addStreamInfo('audio', {'codec': 'aac', 'channels': 2})
    except:
        pass
    item.setProperty('fanart_image', fanart)
    item.setProperty('IsPlayable', 'true')
    if quality_mode:
        contextmenu = []
        if 'episode' in infoLabels.keys():
            episode = infoLabels['episode']
        else:
            episode = -1
        if 'season' in infoLabels.keys():
            season = infoLabels['season']
        else:
            season = -1
        if 'TVShowTitle' in infoLabels.keys():
            show_title = infoLabels['TVShowTitle']
        else:
            show_title = ''
        quailty_u = sys.argv[0] + '?url=' + urllib.quote_plus('<join>'.join([
            show_title,
            str(season),
            str(episode), thumb,
            base64.b64encode(displayname), quality_mode, video_url
        ])) + '&mode=_contextmenu' + '&sitemode=select_quality'
        contextmenu.append(
            (smart_utf8(xbmcaddon.Addon(id=ADDONID).getLocalizedString(39022)),
             'XBMC.PlayMedia(%s)' % quailty_u))
        item.addContextMenuItems(contextmenu)
    xbmcplugin.addDirectoryItem(pluginHandle,
                                url=video_url,
                                listitem=item,
                                isFolder=False)