Better handle bad names, improve browser uri handler

Play videos in browser rather than in a separate application window
This commit is contained in:
Jack 2016-01-12 12:42:32 -05:00
parent 12cd06cae5
commit 120d7edf12
2 changed files with 83 additions and 37 deletions

View file

@ -1,4 +1,4 @@
import sqlite3 from lbrynet.core.Error import UnknownNameError
from lbrynet.lbryfile.StreamDescriptor import LBRYFileStreamType from lbrynet.lbryfile.StreamDescriptor import LBRYFileStreamType
from lbrynet.lbryfile.client.LBRYFileDownloader import LBRYFileSaverFactory, LBRYFileOpenerFactory from lbrynet.lbryfile.client.LBRYFileDownloader import LBRYFileSaverFactory, LBRYFileOpenerFactory
from lbrynet.lbryfile.client.LBRYFileOptions import add_lbry_file_to_sd_identifier from lbrynet.lbryfile.client.LBRYFileOptions import add_lbry_file_to_sd_identifier
@ -18,14 +18,17 @@ from datetime import datetime
import logging import logging
import os import os
import sys import sys
import sqlite3
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class DummyDownloader(object): class DummyDownloader(object):
def __init__(self, directory, file_name): def __init__(self, directory, file_name):
self.download_directory = directory self.download_directory = directory
self.file_name = file_name self.file_name = file_name
class DummyStream(object): class DummyStream(object):
def __init__(self, row): def __init__(self, row):
download_directory = os.path.join(*row[2].split('/')[:-1]) download_directory = os.path.join(*row[2].split('/')[:-1])
@ -97,6 +100,8 @@ class LBRYDaemon(xmlrpc.XMLRPC):
self.session_settings = None self.session_settings = None
self.data_rate = 0.5 self.data_rate = 0.5
self.max_key_fee = 100.0 self.max_key_fee = 100.0
self.db = None
self.cur = None
return defer.succeed(None) return defer.succeed(None)
def _disp_startup(): def _disp_startup():
@ -115,6 +120,7 @@ class LBRYDaemon(xmlrpc.XMLRPC):
d.addCallback(lambda _: self._setup_lbry_file_manager()) d.addCallback(lambda _: self._setup_lbry_file_manager())
d.addCallback(lambda _: self._setup_lbry_file_opener()) d.addCallback(lambda _: self._setup_lbry_file_opener())
d.addCallback(lambda _: self._setup_fetcher()) d.addCallback(lambda _: self._setup_fetcher())
d.addCallback(lambda _: self._setup_daemon_db())
d.addCallback(lambda _: _disp_startup()) d.addCallback(lambda _: _disp_startup())
d.callback(None) d.callback(None)
@ -172,6 +178,33 @@ class LBRYDaemon(xmlrpc.XMLRPC):
return d return d
return defer.succeed(True) return defer.succeed(True)
def _setup_daemon_db(self):
self.db = sqlite3.connect(os.path.join(self.db_dir, 'daemon.sqlite'))
self.cur = self.db.cursor()
query = "create table if not exists history \
(stream_hash char(96) primary key not null,\
uri text not null, \
path text not null);"
self.cur.execute(query)
self.db.commit()
r = self.cur.execute("select * from history")
files = r.fetchall()
print "Checking files in download history still exist, pruning records of those that don't"
for file in files:
if not os.path.isfile(file[2]):
print "Couldn't find", file[2], ", removing record"
self.cur.execute("delete from history where stream_hash='" + file[0] + "'")
self.db.commit()
print "Done checking records"
return defer.succeed(None)
def _get_settings(self): def _get_settings(self):
d = self.settings.start() d = self.settings.start()
d.addCallback(lambda _: self.settings.get_lbryid()) d.addCallback(lambda _: self.settings.get_lbryid())
@ -303,6 +336,9 @@ class LBRYDaemon(xmlrpc.XMLRPC):
log.debug('[' + str(datetime.now()) + ']' + ' Downloading: ' + str(stream.stream_hash)) log.debug('[' + str(datetime.now()) + ']' + ' Downloading: ' + str(stream.stream_hash))
return defer.succeed(None) return defer.succeed(None)
if history == 'UnknownNameError':
return 'UnknownNameError'
if not history: if not history:
stream = GetStream(self.sd_identifier, self.session, self.session.wallet, self.lbry_file_manager, stream = GetStream(self.sd_identifier, self.session, self.session.wallet, self.lbry_file_manager,
max_key_fee=self.max_key_fee, data_rate=self.data_rate) max_key_fee=self.max_key_fee, data_rate=self.data_rate)
@ -348,60 +384,43 @@ class LBRYDaemon(xmlrpc.XMLRPC):
return d return d
def _check_history(self, name, metadata): def _check_history(self, name, metadata):
con = sqlite3.connect(os.path.join(self.db_dir, 'daemon.sqlite')) if metadata == 'UnknownNameError':
cur = con.cursor() return 'UnknownNameError'
query = "create table if not exists history \ r = self.cur.execute("select * from history where stream_hash='" + metadata['stream_hash'] + "'")
(stream_hash char(96) primary key not null,\
uri text not null, \
path text not null);"
cur.execute(query)
con.commit()
r = cur.execute("select * from history where stream_hash='" + metadata['stream_hash'] + "'")
files = r.fetchall() files = r.fetchall()
if files: if files:
if not os.path.isfile(files[0][2]): if not os.path.isfile(files[0][2]):
print "Couldn't find", files[0][2], ", trying to redownload it" print "Couldn't find", files[0][2], ", trying to redownload it"
cur.execute("delete from history where stream_hash='" + files[0][0] + "'") self.cur.execute("delete from history where stream_hash='" + files[0][0] + "'")
con.commit() self.db.commit()
con.close()
return [] return []
else: else:
con.close()
return files return files
else: else:
con.close()
return files return files
def _add_to_history(self, name, path): def _add_to_history(self, name, path):
con = sqlite3.connect(os.path.join(self.db_dir, 'daemon.sqlite')) if path == 'UnknownNameError':
cur = con.cursor() return 'UnknownNameError'
query = "create table if not exists history \ r = self.cur.execute("select * from history where stream_hash='" + path['stream_hash'] + "'")
(stream_hash char(96) primary key not null,\
uri text not null, \
path text not null);"
cur.execute(query)
con.commit()
r = cur.execute("select * from history where stream_hash='" + path['stream_hash'] + "'")
files = r.fetchall() files = r.fetchall()
if not files: if not files:
vals = path['stream_hash'], name, path['path'] vals = path['stream_hash'], name, path['path']
r = cur.execute("insert into history values (?, ?, ?)", vals) self.cur.execute("insert into history values (?, ?, ?)", vals)
con.commit() self.db.commit()
else: else:
print 'Already downloaded', path['stream_hash'], '->', path['path'] print 'Already downloaded', path['stream_hash'], '->', path['path']
con.close()
return path['path'] return path
def xmlrpc_get_settings(self): def xmlrpc_get_settings(self):
""" """
Get LBRY payment settings Get LBRY payment settings
""" """
if not self.session_settings: if not self.session_settings:
self.session_settings = {'data_rate': self.data_rate, 'max_key_fee': self.max_key_fee} self.session_settings = {'data_rate': self.data_rate, 'max_key_fee': self.max_key_fee}
@ -454,6 +473,7 @@ class LBRYDaemon(xmlrpc.XMLRPC):
print 'Shutting down lbrynet daemon' print 'Shutting down lbrynet daemon'
d = self._shutdown() d = self._shutdown()
d.addCallback(lambda _: self.db.close())
d.addCallback(lambda _: _disp_shutdown()) d.addCallback(lambda _: _disp_shutdown())
d.addCallback(lambda _: reactor.stop()) d.addCallback(lambda _: reactor.stop())
@ -482,8 +502,7 @@ class LBRYDaemon(xmlrpc.XMLRPC):
d = defer.Deferred() d = defer.Deferred()
d.addCallback(lambda _: self.session.wallet.get_stream_info_for_name(name)) d.addCallback(lambda _: self.session.wallet.get_stream_info_for_name(name))
d.addErrback(lambda _: 'UnknownNameError') d.addCallbacks(_disp, lambda _: str('UnknownNameError'))
d.addCallback(_disp)
d.callback(None) d.callback(None)
return d return d
@ -559,7 +578,6 @@ class LBRYDaemon(xmlrpc.XMLRPC):
d.addCallback(lambda hist: self._download_name(hist, name)) d.addCallback(lambda hist: self._download_name(hist, name))
d.addCallback(lambda _: self._path_from_name(name)) d.addCallback(lambda _: self._path_from_name(name))
d.addCallback(lambda path: self._add_to_history(name, path)) d.addCallback(lambda path: self._add_to_history(name, path))
d.addCallback(lambda _: self._path_from_name(name))
return d return d

View file

@ -1,6 +1,11 @@
import os
import json
import webbrowser import webbrowser
import xmlrpclib, sys import xmlrpclib, sys
def render_video(path):
r = r'<center><video src="' + path + r'" controls width="960" height="720"></center>'
return r
def main(args): def main(args):
if len(args) == 0: if len(args) == 0:
@ -12,9 +17,32 @@ def main(args):
print 'Too many args', args print 'Too many args', args
else: else:
daemon.download_name(str(args[0])[7:]) if args[0][7:] != 'settings':
path = daemon.path_from_name(args[0][7:])[0]['path'] r = daemon.get(args[0][7:])
webbrowser.open('file://' + path) print r
path = r['path']
if path[0] != '/':
path = '/' + path
print path
filename = path.split('/')[len(path.split('/')) - 1]
extension = path.split('.')[len(path.split('.')) - 1]
if extension in ['mp4', 'flv', 'mov']:
h = str(render_video(path))
f = open('lbry.html', 'w')
f.write(h)
f.close()
webbrowser.open('file://' + os.path.join(os.getcwd(), 'lbry.html'))
else:
webbrowser.open('file://' + path)
else:
r = daemon.get_settings()
f = open('lbry.html', 'w')
f.write("<body>" + json.dumps(r) + "</body>")
f.close()
webbrowser.open('file://' + os.path.join(os.getcwd(), 'lbry.html'))
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv[1:]) main(sys.argv[1:])