#!/bin/python

# From https://webapps.stackexchange.com/questions/72787/how-to-create-a-youtube-playlist-from-a-list-of-links
# Only adds youtube links!

import os, io
import webbrowser
import urllib.request, urllib.error, urllib.parse

inputFileName = 'titles.txt'

def ReadMultipleDataFrom(thisTextFile, thisPattern):
    inputData = []
    file = open(thisTextFile, "r")
    for iLine in file:
        if iLine.startswith(thisPattern):
            iLine = iLine.rstrip()
            # print(iLine)
        if ('v=') in iLine: # https://www.youtube.com/watch?v=aBcDeFGH
            iLink = iLine.split('v=')[1]
            iLink = iLink.split('&')[0]
            inputData.append(iLink)
            # print(iLink)
        if ('be/') in iLine: # https://youtu.be/aBcDeFGH
            iLink =  iLine.split('be/')[1]
            iLink = iLink.split('&')[0]
            inputData.append(iLink)
            # print(iLink)
    return inputData

videoLinks =  ReadMultipleDataFrom(inputFileName, "https")
listOfVideos = "http://www.youtube.com/watch_videos?video_ids=" + ','.join(videoLinks)
response = urllib.request.urlopen(listOfVideos)
playListLink = response.geturl()
playListLink = playListLink.split('list=')[1]
playListURL = "https://www.youtube.com/playlist?list="+playListLink+"&disable_polymer=true"
webbrowser.open(playListURL)