Exemplo n.º 1
0
def main():
    search = input("Enter songname / lyrics / artist ... or whatever\n> ")
    if search == "":
        sys.exit()

    print("Searching ...")

    # Magic happens here.
    search = qp(search)
    response = urlopen("https://www.youtube.com/results?search_query=" + search)
    html = response.read()
    soup = BeautifulSoup(html, "html.parser")
    for link in soup.find_all("a"):
        if "/watch?v=" in link.get("href"):
            # May change when YouTube gets updated in the future.
            video_link = link.get("href")
            break

    # Print title and prompt to download
    title = soup.find("a", "yt-uix-tile-link").text
    print("Found: " + title)
    prompt = input("Download song (Y/n)? ")
    if prompt.lower() == "n":
        return

    # Download the song.
    print("Downloading...")
    download(video_link)
    print("Done!")
    return
Exemplo n.º 2
0
def create_quote(POST={},
                 GET={},
                 ENVIRO={},
                 CLIENT_STATE={},
                 COOKIES={},
                 CONTEXT={},
                 TEMPLATE='',
                 TEMPLATE_ENGINE=None,
                 CSB='',
                 TEMPLATE_STACK={}):

    _key = int(GET.get('incdt_id', ['-1'])[0])
    if _key < 0:
        return m.client_redirect(ENVIRO, '/list_services', '303', CLIENT_STATE,
                                 COOKIES, CSB)

    q_str = """select xmag.create_quote_from_incident(%(key)s) as quhead_id """
    _r = m.run_sql_command(ENVIRO.get('CONN'), q_str, {'key': _key})

    if _r[0]['quhead_id'] > 1:
        return m.client_redirect(ENVIRO,
                                 '/edit_quote?quhead_id=' + _r[0]['quhead_id'],
                                 '303', CLIENT_STATE, COOKIES, CSB)

    return m.client_redirect(ENVIRO, '/list_services?message=',
                             +qp('Failed to Create Quote Template'), '303',
                             CLIENT_STATE, COOKIES, CSB)
Exemplo n.º 3
0
def change_password(url, login, pass_temp):
    r = requests.get(url=f"{url}user/passwordforgotten.php?action=val=
idatenewpassword&username={qp(login)}&passwordhash={hash(pass_temp)}",
                     allow_redirects=False, verify=False)
    if r.status_code == 302:
        if DEBUG:
            print(f"    [*] Password changed: {pass_temp}")
        return 1
    return 0
Exemplo n.º 4
0
def main():
    argument_string = ' '.join(sys.argv[1:])
    search = ''

    # to avoid empty inputs
    if not sys.argv[1:]:
        while search == '':
            search = raw_input('Enter query\n')
        search = qp(search)
        downloaded = query_and_download(search)
Exemplo n.º 5
0
    def post(self, request, *args, **kwargs):
        try:
            order = Order.objects.get(transaction_id=request.POST['unique_id'])
            order.billed_total = request.POST['amount']
            order.billed_datetime = request.POST['date_time']
            order.save()
            # send emails
            all_orders = order.orderitem_set.all()
            workshop = all_orders[0].rate.workshop
            subject = 'Confirmation of payment - %s' % workshop.title
            plaintext_msg = 'Please enable HTML viewing'
            contact = '%s <%s>' % (qp(order.contact_name), order.contact_email)
            attendees = ['%s <%s>' % (qp(i.name), i.email) for i in all_orders]
            admins = ['%s <%s>' % (qp(i[0]), i[1]) for i in settings.ADMINS]

            body = '<html><h1>%s</h1>' % workshop.title
            body += '<h2>Workshop Details</h2>'
            body += '<div>%s</div>' % markdownify(workshop.email_description)
            body += '<div><h2>Order Details</h2>'
            body += '<p>Orderer: %s (%s)</p>' % (order.contact_name,
                                                 order.contact_email)
            body += '<h3>Orders:</h3><ul>'
            for oi in all_orders:
                body += '<li>%s (%s): %s</li>' % (oi.name, oi.email, oi.rate)
            body += '</ul></div>'
            body += '</html>'

            msg = EmailMultiAlternatives(subject,
                                         plaintext_msg,
                                         '*****@*****.**',
                                         to=[contact],
                                         cc=attendees,
                                         bcc=admins)
            msg.attach_alternative(body, "text/html")
            msg.send()
        except (Order.DoesNotExist, KeyError) as e:
            logger.error('%s: %s' % (e, request.body))
            return HttpResponse(status=400)
        return HttpResponse()
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        try:
            order = Order.objects.get(transaction_id=request.POST['unique_id'])
            order.billed_total = request.POST['amount']
            order.billed_datetime = request.POST['date_time']
            order.save()
            # send emails
            all_orders = order.orderitem_set.all()
            workshop = all_orders[0].rate.workshop
            subject = 'Confirmation of payment - %s' % workshop.title
            plaintext_msg = 'Please enable HTML viewing'
            contact = '%s <%s>' % (qp(order.contact_name), order.contact_email)
            attendees = ['%s <%s>' % (qp(i.name), i.email) for i in all_orders]
            admins = ['%s <%s>' % (qp(i[0]), i[1]) for i in settings.ADMINS]

            body = '<html><h1>%s</h1>' % workshop.title
            body += '<h2>Workshop Details</h2>'
            body += '<div>%s</div>' % markdownify(workshop.email_description)
            body += '<div><h2>Order Details</h2>'
            body += '<p>Orderer: %s (%s)</p>' % (order.contact_name,
                                                 order.contact_email)
            body += '<h3>Orders:</h3><ul>'
            for oi in all_orders:
                body += '<li>%s (%s): %s</li>' % (oi.name, oi.email, oi.rate)
            body += '</ul></div>'
            body += '</html>'

            msg = EmailMultiAlternatives(subject, plaintext_msg,
                                         '*****@*****.**',
                                         to=[contact],
                                         cc=attendees,
                                         bcc=admins)
            msg.attach_alternative(body, "text/html")
            msg.send()
        except (Order.DoesNotExist, KeyError) as e:
            logger.error('%s: %s' % (e, request.body))
            return HttpResponse(status=400)
        return HttpResponse()
Exemplo n.º 7
0
def setup():
    from urllib.parse import quote_plus as qp
    #make_online_following_file()
    config = {}
    redirect_uri = "https://puffydrake.com/oauth.php"
    print(
        'First, visit https://oauth.picarto.tv/clients and create a new client named whatever. set the return URI to %s'
        % (redirect_uri))
    print('Then enter the client ID and client secret')
    client_id = input("client_id: ")
    client_secret = input("client_secret: ")
    print("Visit the below URL, then paste the 'code' as prompted")
    print(
        'https://oauth.picarto.tv/authorize?response_type=code&client_id=%s&redirect_uri=%s&scope=readpriv'
        % (client_id, qp(redirect_uri)))
    code = input("> ")
    data = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": redirect_uri,
        "client_id": client_id,
        "client_secret": client_secret
    }
    r = requests.post('https://oauth.picarto.tv/token', data=data)
    if r.status_code != 200:
        print("Something went wrong. Check out below and try again.")
        print(r.text)
        exit()
    access_token = r.json()['access_token']
    config['picarto_bearer'] = access_token
    print("Great! Now enter your Simplepush API key or press 'enter' to skip.")
    simplepush_key = input("> ")
    config['simplepush_key'] = simplepush_key
    print(
        "If you have an IFTTT account, you can connect the Webook channel to make use of it."
    )
    print(
        "This will trigger event 'picarto_online' and send the channel name as 'value1'."
    )
    print("Enter your IFTTT key for Webook channel, or press enter to skip.")
    ifttt_key = input("> ")
    config['ifttt_key'] = ifttt_key
    config["adult"] = True
    config["gaming"] = False
    print(
        "Great! We've defaulted to show adult streams but not gaming. You can change this in config.json later."
    )
    with open("config.json", "w") as f:
        json.dump(config, f)
Exemplo n.º 8
0
def grab_albumart(search=''):
    search = qp(search)
    site = "https://www.google.com/search?site=&tbm=isch&source=hp&biw=1112&bih=613&q="+search+"&oq=backst&gs_l=img.3.0.0l10.1011.3209.0.4292.8.7.1.0.0.0.246.770.0j3j1.4.0..3..0...1.1.64.img..3.5.772.KyXkrVfTLT4#tbm=isch&q=back+street+boys+I+want+it+that+way"
    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
           'Accept-Encoding': 'none',
           'Accept-Language': 'en-US,en;q=0.8',
           'Connection': 'keep-alive'}
    req = makeRequest(site, hdr)

    content = str(req.content)
    end =  content.find('jpg')
    start= content[:end].rfind('http')

    return content[start:end+3]
Exemplo n.º 9
0
def main():
    """ Run the Program """

    query =qp(get_search_term())

    url = 'https://kat.cr/usearch/' + query

    try:
        print ('Searching....')
        torrent_list = get_torrent_list(url)

    except Exception as e:
        print (e)
        exit()

    print('Found:', '\n'.join(list_torrents(torrent_list)))

    try:
        choice = raw_input('Choose the torrent: ')

        while not(choice.isdigit()) or not(0 <= int(choice) < len(torrent_list)):
            print("Invalid Choice.  Try again!")
            choice = raw_input('Choose the torrent: ')

        title, torrent_link = torrent_list[int(choice)]

        user_choice = raw_input('Stream "%s"? (y/n) ' % title)

        if user_choice.upper() != "Y" :
            sys.exit()

    except:
        title, torrent_link = torrent_list[0]

    print ('Streaming Torrent: ' + title)

    final_url = 'https://kat.cr' + torrent_link
    torrent_page = open_url(final_url)
    soup = BeautifulSoup(torrent_page.text, 'html.parser')
    final = 'https:' + soup.find_all('a', class_='siteButton')[0].get('href')

    os.system('peerflix ' + final + ' -a --vlc')
Exemplo n.º 10
0
def email_cert(POST={},
               GET={},
               ENVIRO={},
               CLIENT_STATE={},
               COOKIES={},
               CONTEXT={},
               TEMPLATE='',
               TEMPLATE_ENGINE=None,
               CSB='',
               TEMPLATE_STACK={}):
    if 'calhead_id' in GET:
        _key = int(''.join(GET.get('calhead_id', '-1')))
    elif 'calhead_id' in POST:
        _key = int(''.join(POST.get('calhead_id', '-1')))

    _sql = "select email_certificate(%(calhead_id)s) as message;"
    _r = m.run_sql_command(ENVIRO.get('CONN'), _sql, {'calhead_id': _key})
    return m.client_redirect(ENVIRO,
                             '/list_cal?message=' + qp(_r[0]['message']),
                             '303', CLIENT_STATE, COOKIES, CSB)
Exemplo n.º 11
0
    def performYoutubeSearch(self, query):
        """ Perform a Youtube Search """
        response = urlopen("https://www.youtube.com/results?search_query=" + qp(query))
        html = response.read()
        soup = BeautifulSoup(html, "html.parser")
        for link in soup.find_all("a"):
            if "/watch?v=" in link.get("href"):
                # May change when Youtube gets updated in the future.
                video_link = link.get("href")
                break

        result = soup.find("a", "yt-uix-tile-link")

        if result is not None:
            title = soup.find("a", "yt-uix-tile-link").text
            title = title.encode("latin-1", "ignore").decode("utf-8", "ignore")
            print("Found: " + title)
            return video_link
        else:
            return False
def main():

    search = ''
    while search.strip() == '':
        search = raw_input('Enter songname/lyrics/artist/url or other\n> ')

    print('Searching...')
    print(search)

    if is_url(search):
        print('You gave me an url')
        video_url = search
        download_from_url(video_url)
        print('Finished downloading link!')
        return
        sys.exit()

    search = qp(search)
    available = search_videos(search)

    if not available:
        print('No results found matching your query.')
        sys.exit()

    print("Found:", '\n', '\n'.join(list_movies(available)))
    print('-----------------------------------------------------------------')

    print('\n')

    choice = ''
    while choice.strip() == '':
        choice = raw_input('Pick one to download: ')

    title, video_link = available[int(choice)]

    # prompt = raw_input("Download (y/n)? ")
    # if prompt != "y":
    #     sys.exit()

    video_url = 'http://www.youtube.com' + video_link
    download_from_url(video_url)
Exemplo n.º 13
0
    def performYoutubeSearch(self, query):
        """ Perform a Youtube Search """
        response = urlopen('https://www.youtube.com/results?search_query=' +
                           qp(query))
        html = response.read()
        soup = BeautifulSoup(html, 'html.parser')
        for link in soup.find_all('a'):
            if '/watch?v=' in link.get('href'):
                # May change when Youtube gets updated in the future.
                video_link = link.get('href')
                break

        result = soup.find('a', 'yt-uix-tile-link')

        if result is not None:
            title = soup.find('a', 'yt-uix-tile-link').text
            title = title.encode('latin-1', 'ignore').decode('utf-8', 'ignore')
            print("Found: " + title)
            return video_link
        else:
            return False
Exemplo n.º 14
0
def main():
   
    search = ''
    while search.strip() == '':
        search = raw_input('Enter songname/lyrics/artist or other\n> ')
    search = qp(search)

    print('Searching...')
    available = search_videos(search)

    if not available:
        print('No results found matching your query.')
        sys.exit()

    print("Found:", '\n', '\n'.join(list_movies(available)))
    print ('-----------------------------------------------------------------')

    print('\n')

    choice = ''
    while choice.strip() == '':
        choice = raw_input('Pick one: ')

    title, video_link = available[int(choice)]

    prompt = raw_input("Download (y/n)? ")
    if prompt != "y":
        sys.exit()

    command_tokens = [
        'youtube-dl',
        '--extract-audio',
        '--audio-format mp3',
        '--audio-quality 0',
        'http://www.youtube.com/' + video_link]

    command = ' '.join(command_tokens)

    print('Downloading...')
    os.system(command)
Exemplo n.º 15
0
def save_incident(POST={},
                  GET={},
                  ENVIRO={},
                  CLIENT_STATE={},
                  COOKIES={},
                  CONTEXT={},
                  TEMPLATE='',
                  TEMPLATE_ENGINE=None,
                  CSB='',
                  TEMPLATE_STACK={}):

    q_str = """Update incident set 
           incdt_descrip = %()s
        where incdt_id = %()s"""
    _incdt = m.run_sql_command(ENVIRO.get('CONN'), q_str, {'key': p_key})

    q_str = """update cntct set
            cntct_first_name = %()s,
            cntct_last_name = %()s , 
            cntct_phone = %()s,
            cntct_email = %()s
        where cntct_id = %()s"""
    _cntct = m.run_sql_command(ENVIRO.get('CONN'), q_str, {'key': p_key})

    q_str = """update addr set
            addr_line1 = %()s,
            addr_line2 =%()s ,
            addr_line3 = %()s,
            addr_city = %()s,
            addr_state = %()s 
        where addr_id = %()s"""

    _addr = m.run_sql_command(ENVIRO.get('CONN'), q_str, {'key': p_key})

    return m.client_redirect(ENVIRO, '/edit_incdt?message=',
                             +qp('Failed to Create Quote Template'))
Exemplo n.º 16
0
def main():
    """
    Run the program session
    """
    argument_string = ' '.join(sys.argv[1:])
    search = ''

    # No command-line arguments
    if not sys.argv[1:]:
        # We do not want to accept empty inputs :)
        while search == '':
            search = raw_input(
                'Enter songname / lyrics / artist.. or whatever\n> ')
        search = qp(search)
        downloaded = query_and_download(search)

    # Command-line arguments detected!
    else:
        # No flags at all are specified
        if not search_uses_flags(argument_string, '-s', '-i', '-f', '-p',
                                 '-q'):
            search = qp(' '.join(sys.argv[1:]))
            downloaded = query_and_download(search)

        # No input flags are specified
        elif not search_uses_flags(argument_string, '-s', '-i', '-f'):
            # Default to -s
            lyrics = argument_string.replace('-p', '').replace('-q', '')
            search = qp(lyrics)
            downloaded = query_and_download(search,
                                            not search_uses_flags('-p'),
                                            search_uses_flags('-q'))

        # Some input flags are specified
        else:
            # Lots of parser-building fun!
            import argparse
            parser = argparse.ArgumentParser(
                description='Instantly download any song!')
            parser.add_argument('-p',
                                action='store_false',
                                dest='has_prompt',
                                help="Turn off download prompts")
            parser.add_argument(
                '-q',
                action='store_true',
                dest='is_quiet',
                help="Run in quiet mode. Automatically turns off prompts.")
            parser.add_argument('-s',
                                action='store',
                                dest='song',
                                nargs='+',
                                help='Download a single song.')
            parser.add_argument(
                '-l',
                action='store',
                dest='songlist',
                nargs='+',
                help=
                'Download a list of songs, with lyrics separated by a comma (e.g. "i tried so hard and got so far, blackbird singing in the dead of night, hey shawty it\'s your birthday).'
            )
            parser.add_argument(
                '-f',
                action='store',
                dest='file',
                nargs='+',
                help=
                'Download a list of songs from a file input. Each line in the file is considered one song.'
            )

            # Parse and check arguments
            results = parser.parse_args()

            song_list = []
            if results.song:
                song_list.append(qp(' '.join(results.song)))

            if results.songlist:
                songs = ' '.join(results.songlist)
                song_list.extend([qp(song) for song in songs.split(',')])

            if results.file:
                with open(results.file[0], 'r') as f:
                    songs = f.readlines()
                    # strip out any empty lines
                    songs = filter(None, (song.rstrip() for song in songs))
                    # strip out any new lines
                    songs = [qp(song.strip()) for song in songs if song]
                    song_list.extend(songs)

            prompt = True if results.has_prompt else False
            quiet = True if results.is_quiet else False

            downloads = []
            for song in song_list:
                downloads.append(query_and_download(song, prompt, quiet))

            print('Downloaded: %s' % ', '.join(downloads))
Exemplo n.º 17
0
def query_and_download(search, has_prompts=True, is_quiet=False):
    """
    Queries the internet for given lyrics and downloads them into the current working directory.
    If has_prompts is False, will download first available song.
    If is_quiet is True, will run beautiful-soup in quiet mode. Prompts will also automatically be turned
                         off in quiet mode. This is mainly so that instantmusic can be run as a background process.
    Returns the title of the video downloaded from.
    """
    if not is_quiet:
        iprint('Searching...')

    available = search_videos(search)

    if not is_quiet:
        if not available:
            iprint('No results found matching your query.')
            sys.exit(2)  # Indicate failure using the exit code
        else:
            if has_prompts:
                iprint('Found:', '\n'.join(list_movies(available)))

    # We only ask the user which one they want if prompts are on, of course
    if has_prompts and not is_quiet:
        choice = raw_input('Pick one: ')
        while not (choice.isdigit()) or not (0 <= int(choice) <
                                             len(available)):
            iprint("Oups, that was wrong. Try again!")
            choice = raw_input('Pick one: ')
        title, video_link = available[int(choice)]

        valid = ['Y', 'y', '']
        prompt = raw_input('Download "%s"? (y/n) ' % title)
        if prompt.lower() not in valid:
            sys.exit()
    # Otherwise, just download the first in available list
    else:
        title, video_link = available[0]

    command_tokens = [
        'youtube-dl',
        '--extract-audio',
        '--audio-format mp3',
        '--audio-quality 9',  #worse quality
        #'--restrict-filenames',
        '--output \'%(title)s.%(ext)s\'',
        'https://www.youtube.com' + video_link
    ]

    if is_quiet:
        command_tokens.insert(1, '-q')

    command = ' '.join(command_tokens)

    # Youtube-dl is a proof that god exists.
    if not is_quiet:
        iprint('Downloading')
    os.system(command)

    # Fixing id3 tags
    try:
        iprint('Fixing id3 tags')
        list_name = title
        artist = ''
        track_name = title
        if '-' in title:
            list_name = title.split('-')
            artist = list_name[0]
            track_name = list_name[1]
        album_name = ''
        try:
            try:
                audiofile = eyed3.load((title + '.mp3'))
            except:
                audiofile = eyed3.load((title + '.m4a'))

            url = 'https://www.google.com/search?q=' + qp(title)
            req = makeRequest(url, {})
            response = req.content
            result = response
            lyrics_html = get_lyrics_url(result)
            a = makeRequest(lyrics_html, {})
            iprint(lyrics_html)
            html_doc = a.content
            soup = BeautifulSoup(html_doc, 'html.parser')
            try:
                album_name = soup.find(id="album-name-link").text
            except:
                iprint('Cant get album name')
            try:
                lyrics = ('')
                raw_lyrics = (soup.findAll('p', attrs={'class': 'verse'}))
                for each_line in raw_lyrics:
                    lyrics = lyrics + str(each_line.get_text()) + '\n'
                iprint(lyrics)
                audiofile.tag.lyrics.set(u'' + lyrics)
            except:
                iprint('cant get lyrics')
        except Exception as e:
            iprint(e)
            iprint('error getting album and lyrics')

        iprint(artist, track_name, album_name)

        def fix_string(s):
            location = s.find('[')
            if location != -1:
                return s[:location].strip()
            else:
                return s.strip()

        artist = fix_string(artist)
        track_name = fix_string(track_name)
        album_name = fix_string(album_name)

        audiofile.tag.artist = normalize(artist)
        audiofile.tag.title = normalize(track_name)
        audiofile.tag.album = normalize(album_name)

        search = title[:-4]
        iprint('Downloading album art..')
        image_link = grab_albumart(search)
        title = normalize(title)
        iprint('Fixing ' + title)
        eyed3.log.setLevel("ERROR")
        if audiofile.tag is None:
            audiofile.tag = eyed3.id3.Tag()
            audiofile.tag.file_info = eyed3.id3.FileInfo("foo.id3")
        response = makeRequest(image_link, {}).content
        imagedata = response

        audiofile.tag.images.set(0, imagedata, "image/jpeg", u"Album Art")
        audiofile.tag.save()
        iprint('Fixed')
    except Exception as e:
        iprint(e)
        iprint('couldnt get album art')

    return title
Exemplo n.º 18
0
]:
    for node in tree.xpath("//*[@src='../../_static/%s']" % src):
        node.attrib['src'] = src
    src_fp = os.path.join('.', 'build', 'preview', '_static', src)
    shutil.copy(src_fp, tutorial_fp)

css_fp = os.path.join(tutorial_fp, 'bootstrap.min.css')
with open(css_fp, 'r') as fh:
    css = fh.read()
css = css.replace('../fonts/', './fonts/')
with open(css_fp, 'w') as fh:
    fh.write(css)

# Clean up q2view links
for node in tree.xpath('//a'):
    if qp(tutorial_data_url) in node.attrib['href']:
        node.attrib['href'] = node.attrib['href'].replace(
            qp(tutorial_data_url), qp(s3_url))
        node.attrib['target'] = '_blank'

# Clean up download links
for node in tree.xpath('//a'):
    if tutorial_data_url in node.attrib['href']:
        node.attrib['href'] = node.attrib['href'].replace(
            tutorial_data_url, s3_url)

# Clean up xrefs
for node in tree.xpath('//a'):
    if node.attrib['href'].startswith('../'):
        node.attrib['href'] = node.attrib['href'].replace(
            '../', tutorials_url, 1)
def main():
    """
    Run the program session
    """
    argument_string = ' '.join(sys.argv[1:])
    search = ''

    # No command-line arguments
    if not sys.argv[1:]:
        # We do not want to accept empty inputs :)
        while search == '':
            search = raw_input('Enter songname/ lyrics/ artist.. or whatever\n> ')
        search = qp(search)
        downloaded = query_and_download(search)

    # Command-line arguments detected!
    else:
        # No flags at all are specified
        if not search_uses_flags(argument_string, '-s', '-i', '-f', '-p', '-q'):
            search = qp(' '.join(sys.argv[1:]))
            downloaded = query_and_download(search)

        # No input flags are specified
        elif not search_uses_flags(argument_string, '-s', '-i', '-f'):
            # Default to -s
            lyrics = argument_string.replace('-p', '').replace('-q', '')
            search = qp(lyrics)
            downloaded = query_and_download(search, not search_uses_flags('-p'), search_uses_flags('-q'))

        # Some input flags are specified
        else:
            # Lots of parser-building fun!
            import argparse
            parser = argparse.ArgumentParser(description='Instantly download any song!')
            parser.add_argument('-p', action='store_false', dest='has_prompt', help="Turn off download prompts")
            parser.add_argument('-q', action='store_true', dest='is_quiet', help="Run in quiet mode. Automatically turns off prompts.")
            parser.add_argument('-s', action='store', dest='song', nargs='+', help='Download a single song.')
            parser.add_argument('-l', action='store', dest='songlist', nargs='+', help='Download a list of songs, with lyrics separated by a comma (e.g. "i tried so hard and got so far, blackbird singing in the dead of night, hey shawty it\'s your birthday).')
            parser.add_argument('-f', action='store', dest='file', nargs='+', help='Download a list of songs from a file input. Each line in the file is considered one song.')

            # Parse and check arguments
            results = parser.parse_args()

            song_list = []
            if results.song:
                song_list.append(qp(' '.join(results.song)))

            if results.songlist:
                songs = ' '.join(results.songlist)
                song_list.extend([qp(song) for song in songs.split(',')])

            if results.file:
                with open(results.file[0], 'r') as f:
                    songs = f.readlines()
                    # strip out any empty lines
                    songs = filter(None, (song.rstrip() for song in songs))
                    # strip out any new lines
                    songs = [qp(song.strip()) for song in songs if song]
                    song_list.extend(songs)

            prompt = True if results.has_prompt else False
            quiet = True if results.is_quiet else False

            downloads = []
            for song in song_list:
                downloads.append(query_and_download(song, prompt, quiet))

            print('Downloaded: %s' % ', '.join(downloads))
Exemplo n.º 20
0
def fix_id3_tags(title):
    """fix id3 tags.

    Args:
        title (str): Title.

    Returns:
        str: Modified title.
    """
    print('Fixing id3 tags')
    list_name = title
    artist = ''
    track_name = title
    if '-' in title:
        list_name = title.split('-')
        artist = list_name[0]
        track_name = list_name[1]
    album_name = ''
    if not EYED3_MODULE:
        return title
    try:
        try:
            audiofile = eyed3.load((title + '.mp3'))
        except:
            audiofile = eyed3.load((title + '.m4a'))

        url = 'https://www.google.com/search?q=' + qp(title)
        req = make_request(url, {})
        response = req.content
        result = response
        lyrics_html = get_lyrics_url(result)
        a = make_request(lyrics_html, {})
        print(lyrics_html)
        html_doc = a.content
        soup = BeautifulSoup(html_doc, 'html.parser')
        try:
            album_name = soup.find(id="album-name-link").text
        except:
            print('Cant get album name')
        try:
            lyrics = ('')
            raw_lyrics = (soup.findAll('p', attrs={'class': 'verse'}))
            for each_line in raw_lyrics:
                lyrics = lyrics + str(each_line.get_text()) + '\n'
            print(lyrics)
            # python3.2's flake8 mark this line as error E900, SKIP IT
            audiofile.tag.lyrics.set(u'' + lyrics)  # NOQA
        except:
            print('cant get lyrics')
    except Exception as e:
        print(e)
        print('error getting album and lyrics')

    print(artist, track_name, album_name)

    def fix_string(s):
        location = s.find('[')
        if location != -1:
            return s[:location].strip()
        else:
            return s.strip()

    artist = fix_string(artist)
    track_name = fix_string(track_name)
    album_name = fix_string(album_name)

    audiofile.tag.artist = unicode(artist)
    audiofile.tag.title = unicode(track_name)
    audiofile.tag.album = unicode(album_name)

    search = title[:-4]
    print('Downloading album art..')
    image_link = grab_albumart(search)
    title = unicode(title, errors='replace').encode('utf8')
    print('Fixing ' + title)
    eyed3.log.setLevel("ERROR")
    if audiofile.tag is None:
        audiofile.tag = eyed3.id3.Tag()
        audiofile.tag.file_info = eyed3.id3.FileInfo("foo.id3")
    response = make_request(image_link, {}).content
    imagedata = response

    audiofile.tag.images.set(0, imagedata, "image/jpeg", u"Album Art")
    audiofile.tag.save()
    print('Fixed')

    return title
Exemplo n.º 21
0
    def post(self, request, *args, **kwargs):
        order_data = request.session['order']

        rates = {}
        for ticket in order_data['tickets']:
            rate = Rate.objects.get(id=ticket['rate'])
            if rate not in rates:
                rates[rate] = 1
            else:
                rates[rate] += 1

        for rate, quantity in rates.items():
            if rate.ticket_count + quantity > rate.capacity:
                remaining = rate.capacity - rate.ticket_count
                messages.warning(request, 'There are too many %s tickets in '
                                 'this order. Ticket(s) remaining at this '
                                 'rate: %d.' % (rate.name, remaining))
                return HttpResponseRedirect(
                    reverse('payments:details', kwargs={
                        'slug': order_data['workshop']
                    })
                )

        order = Order.objects.create(contact_email=order_data['email'],
                                     contact_name=order_data['name'],
                                     order_total=order_data['order_total'])
        items = []
        for ticket in order_data['tickets']:
            items.append(OrderItem(order=order, rate_id=ticket['rate'],
                         email=ticket['email'], name=ticket['name'],
                         poster_id=ticket['poster']))
        # Hit the database only once and create all of the OrderItems generated
        OrderItem.objects.bulk_create(items)

        if str(order.order_total) == '0.00':
            payload = {
                'unique_id': str(order.transaction_id),
                'amount': str(order.order_total),
                'date_time': str(order.order_datetime),
            }
            requests.post('https://payment-callback.qiime2.org', data=payload)
            return HttpResponseRedirect('https://workshops.qiime2.org/')

        # Now that the order is saved, clear the session so that they can't
        # resubmit the order
        del request.session['order']

        name = order.contact_name.split(' ')

        payload = {
            'LMID':                    settings.LMID,
            'unique_id':               str(order.transaction_id),
            'sTotal':                  str(order.order_total),
            'webTitle':                settings.PAYMENT_TITLE,
            'Trans_Desc':              settings.PAYMENT_DESCRIPTION,
            'contact_info':            settings.PAYMENT_CONTACT_INFO,
            'BILL_CUSTOMER_EMAIL':     order.contact_email,
            'BILL_CUSTOMER_FIRSTNAME': qp(name[0]),
            'BILL_CUSTOMER_LASTNAME':  qp(name[-1]) if len(name) > 1 else '',
            'note':                    '',  # Placeholder
            'arrayname':               'metadata',
        }

        for i, ticket in enumerate(order_data['tickets']):
            rate = Rate.objects.get(pk=ticket['rate'])
            payload['metadata_item_%s,%s' % (0, i)] = \
                '%s: %s (%s)' % (rate.name, qp(ticket['name']),
                                 ticket['email'])
            payload['metadata_item_%s,%s' % (1, i)] = '1'
            payload['metadata_item_%s,%s' % (2, i)] = str(rate.price)
            payload['metadata_item_%s,%s' % (3, i)] = str(rate.price)
            payload['metadata_item_%s,%s' % (4, i)] = settings.PSF_SPEEDTYPE
            payload['metadata_item_%s,%s' % (5, i)] = settings.PSF_ACCT_NUMBER

        r = requests.post(settings.PAYMENT_URL, data=payload,
                          verify=settings.PAYMENT_CERT_BUNDLE)
        return HttpResponse(r.content, status=r.status_code)
import sys

if sys.version_info > (3, 0):
    from urllib.request import urlopen
    from urllib.parse import quote_plus as qp

    raw_input = input
else:
    from urllib2 import urlopen
    from urllib import quote_plus as qp

search = ""
# We do not want to accept empty inputs :)
while search == "":
    search = raw_input("Enter songname/ lyrics/ artist.. or whatever\n> ")
search = qp(search)

print("Making a Query Request! ")

# Magic happens here.
response = urlopen("https://www.youtube.com/results?search_query=" + search)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
for link in soup.find_all("a"):
    if "/watch?v=" in link.get("href"):
        # May change when Youtube gets updated in the future.
        video_link = link.get("href")
        break

title = soup.find("a", "yt-uix-tile-link").text
print("Found: " + title)
Exemplo n.º 23
0
    def post(self, request, *args, **kwargs):
        order_data = request.session['order']

        rates = {}
        for ticket in order_data['tickets']:
            rate = Rate.objects.get(id=ticket['rate'])
            if rate not in rates:
                rates[rate] = 1
            else:
                rates[rate] += 1

        for rate, quantity in rates.items():
            if rate.ticket_count + quantity > rate.capacity:
                remaining = rate.capacity - rate.ticket_count
                messages.warning(
                    request, 'There are too many %s tickets in '
                    'this order. Ticket(s) remaining at this '
                    'rate: %d.' % (rate.name, remaining))
                return HttpResponseRedirect(
                    reverse('payments:details',
                            kwargs={'slug': order_data['workshop']}))

        order = Order.objects.create(contact_email=order_data['email'],
                                     contact_name=order_data['name'],
                                     order_total=order_data['order_total'])
        items = []
        for ticket in order_data['tickets']:
            items.append(
                OrderItem(order=order,
                          rate_id=ticket['rate'],
                          email=ticket['email'],
                          name=ticket['name'],
                          poster_id=ticket['poster']))
        # Hit the database only once and create all of the OrderItems generated
        OrderItem.objects.bulk_create(items)

        if str(order.order_total) == '0.00':
            payload = {
                'unique_id': str(order.transaction_id),
                'amount': str(order.order_total),
                'date_time': str(order.order_datetime),
            }
            requests.post('https://payment-callback.qiime.org', data=payload)
            return HttpResponseRedirect('https://workshops.qiime.org/')

        # Now that the order is saved, clear the session so that they can't
        # resubmit the order
        del request.session['order']

        name = order.contact_name.split(' ')

        payload = {
            'LMID': settings.LMID,
            'unique_id': str(order.transaction_id),
            'sTotal': str(order.order_total),
            'webTitle': settings.PAYMENT_TITLE,
            'Trans_Desc': settings.PAYMENT_DESCRIPTION,
            'contact_info': settings.PAYMENT_CONTACT_INFO,
            'BILL_CUSTOMER_EMAIL': order.contact_email,
            'BILL_CUSTOMER_FIRSTNAME': qp(name[0]),
            'BILL_CUSTOMER_LASTNAME': qp(name[-1]) if len(name) > 1 else '',
            'note': '',  # Placeholder
            'arrayname': 'metadata',
        }

        for i, ticket in enumerate(order_data['tickets']):
            rate = Rate.objects.get(pk=ticket['rate'])
            payload['metadata_item_%s,%s' % (0, i)] = \
                '%s: %s (%s)' % (rate.name, qp(ticket['name']),
                                 ticket['email'])
            payload['metadata_item_%s,%s' % (1, i)] = '1'
            payload['metadata_item_%s,%s' % (2, i)] = str(rate.price)
            payload['metadata_item_%s,%s' % (3, i)] = str(rate.price)
            payload['metadata_item_%s,%s' % (4, i)] = settings.PSF_SPEEDTYPE
            payload['metadata_item_%s,%s' % (5, i)] = settings.PSF_ACCT_NUMBER

        r = requests.post(settings.PAYMENT_URL,
                          data=payload,
                          verify=settings.PAYMENT_CERT_BUNDLE)
        return HttpResponse(r.content, status=r.status_code)