pandora_scripts/text2edit.py
2014-02-24 17:54:00 +05:30

83 lines
2.3 KiB
Python
Executable file

#!/usr/bin/env python
from __future__ import division
import json
import re
import sys
from optparse import OptionParser
from urllib import quote, unquote
from urlparse import urlparse
import ox
def encode_url(value):
return quote(value.replace(' ', '_'))
def decode_url(value):
return unquote(value.replace('_', ' '))
usage = "usage: %prog [options] text_url [name]"
parser = OptionParser(usage=usage)
parser.add_option('-s', '--settings', dest='settings',
help='path to settings.json', default='settings.json', type='string')
(opts, args) = parser.parse_args()
if not args:
parser.print_help()
sys.exit(1)
try:
settings = json.load(open(opts.settings))
except:
print 'Failed to open "%s" please create valid json file with username/password' % opts.settings
sys.exit(1)
u = urlparse(args[0])
base_url = '%s://%s/' % (u.scheme, u.netloc)
api = ox.API('%sapi/' % base_url)
text_id = unquote(args[0].split('/')[-1].replace('_', ' '))
name = args[1] if len(args) == 2 else ':'.join(text_id.split(':')[1:])
r = api.signin(username=settings['username'], password=settings['password'])
if r['status']['code'] != 200 or 'errors' in r['data']:
print 'failed to login'
sys.exit()
text = api.getText(id=text_id)['data']['text']
clips = []
for link in re.compile('href="([^"]*?)#embed').findall(text):
parts = link[1:].split('/')
if len(parts) == 3 and parts[0] not in ('grid', 'map'):
id = parts[0]
view = parts[1]
if view in ('editor', 'player', 'timeline'):
points = parts[2].split(',')
if len(points) == 3:
points = points[1:]
clips.append({
'item': id,
'in': ox.time2ms(points[0])/1000,
'out': ox.time2ms(points[1])/1000
})
durations = {}
items = list(set([c['item'] for c in clips]))
for item in items:
r = api.get(id=item, keys=['duration'])
durations[item] = r['data']['duration']
for c in clips:
if c['out'] > durations[c['item']]:
print 'fixing', c, 'setting out to', durations[c['item']]
c['out'] = durations[c['item']]
r = api.addEdit(name=name, type='static', clips=clips)
if 'id' in r['data']:
edit_url = '%sedits/%s' % (base_url, encode_url(r['data']['id']))
print edit_url, 'created'
else:
print 'ERROR'
print r