Exemplo n.º 1
0
def addtorrent(context, request):
    u = get_current_user(request)
    announce_url = ('http://%s/%s/announce' % (request.registry.settings['hostname'], u.passkey)).encode('utf-8')
    if request.method=="POST":
        form = AddTorrentForm(request.params)
        if form.validate():
            
            filename = save_torrent(form.torrent_file.data, request)
            abs_filename = os.path.join(request.registry.settings['torrent_dir'], filename)
            info = bencode.bencode(bencode.bdecode(open(abs_filename).read())['info'])
            name = form.name.data
            info_hash = hashlib.sha1(info).hexdigest()
            log.error('INFOHASH: '+info_hash)
            torrent = Torrent()
            torrent.info_hash = info_hash
            torrent.name = unicode(name) 
            torrent.info = {}
            torrent.uploaded_time = datetime.datetime.now()
            torrent.torrent_file = filename
            torrent.last_checked = datetime.datetime.now()
            DBSession.add(torrent)
            DBSession.commit()
            log.error(filename)
        return {'form': form, 'announce': announce_url}
    else:
        form = AddTorrentForm()
        return {'form': form, 'announce': announce_url}
Exemplo n.º 2
0
def addtorrent(context, request):
    u = get_current_user(request)
    announce_url = (
        'http://%s/%s/announce' %
        (request.registry.settings['hostname'], u.passkey)).encode('utf-8')
    if request.method == "POST":
        form = AddTorrentForm(request.params)
        if form.validate():

            filename = save_torrent(form.torrent_file.data, request)
            abs_filename = os.path.join(
                request.registry.settings['torrent_dir'], filename)
            info = bencode.bencode(
                bencode.bdecode(open(abs_filename).read())['info'])
            name = form.name.data
            info_hash = hashlib.sha1(info).hexdigest()
            log.error('INFOHASH: ' + info_hash)
            torrent = Torrent()
            torrent.info_hash = info_hash
            torrent.name = unicode(name)
            torrent.info = {}
            torrent.uploaded_time = datetime.datetime.now()
            torrent.torrent_file = filename
            torrent.last_checked = datetime.datetime.now()
            DBSession.add(torrent)
            DBSession.commit()
            log.error(filename)
        return {'form': form, 'announce': announce_url}
    else:
        form = AddTorrentForm()
        return {'form': form, 'announce': announce_url}
Exemplo n.º 3
0
def login(context, request):
    if request.method == "POST":
        form = LoginForm(request.params)
        if form.validate():
            username = form.username.data
            password = form.password.data

            u = DBSession.query(User).filter_by(username=username).filter_by(
                password=hashlib.sha1(password).hexdigest()).first()
            if u:
                request.session['username'] = username
                request.session['principals'] = [
                    a.principal_name for a in u.principals
                ]
                request.session.save()
                return HTTPFound(location='/')
            else:
                return {
                    'form': form,
                    'error': 'Username or password incorrect'
                }

        else:
            return {'form': form, 'error': None}
    else:
        return {'form': LoginForm(), 'error': None}
Exemplo n.º 4
0
 def validate_username(form, field):
     log.error("validate_username")
     if not re.match('[a-zA-Z0-9-_]+', field.data):
         raise validators.ValidationError(
             'Username may only contain alpha-numeric characters')
     if DBSession.query(User).filter(
             func.lower(User.username) == func.lower(field.data)).first():
         raise validators.ValidationError('Username already taken')
Exemplo n.º 5
0
def signup(context, request):
    if request.method == "POST":
        form = SignupForm(request.params)
        if form.validate():
            u = User(form.username.data, form.password.data)
            u.passkey = "".join([random.choice(string.letters) for x in xrange(16)])
            p = get_principal('group:user')
            u.principals.append(p)
            log.error(form.username.data)
            DBSession.add(u)
            DBSession.commit()
            request.session['flashmessage'] = "Your user has been created! Passkey = "+u.passkey
            request.session.save()
            return HTTPMovedPermanently(location='/')
        else:
            return {'form': form}
    return {'form': SignupForm()}
Exemplo n.º 6
0
def signup(context, request):
    if request.method == "POST":
        form = SignupForm(request.params)
        if form.validate():
            u = User(form.username.data, form.password.data)
            u.passkey = "".join(
                [random.choice(string.letters) for x in xrange(16)])
            p = get_principal('group:user')
            u.principals.append(p)
            log.error(form.username.data)
            DBSession.add(u)
            DBSession.commit()
            request.session[
                'flashmessage'] = "Your user has been created! Passkey = " + u.passkey
            request.session.save()
            return HTTPMovedPermanently(location='/')
        else:
            return {'form': form}
    return {'form': SignupForm()}
Exemplo n.º 7
0
def get_torrent(context, request):
    id_ = request.matchdict['id']
    u = get_current_user(request)
    torrent = DBSession.query(Torrent).filter_by(torrent_id = id_).first()
    abs_filename = os.path.join(request.registry.settings['torrent_dir'], torrent.torrent_file)
    f = open(abs_filename)
    torrentdata = f.read()
    torb = bencode.bdecode(torrentdata)
    
    torb['announce'] = ('http://%s/%s/announce' % (request.registry.settings['hostname'], u.passkey)).encode('utf-8')
    return Response(bencode.bencode(torb), headerlist=[('Content-Type', 'application/x-bittorrent'), ('Content-Disposition', 'attachment; filename=\"'+torrent.name+".torrent\"")])
Exemplo n.º 8
0
def setup(context, request):
    #Setup principals
    try:
        p = Principal('group:user')
        p = Principal('group:admin')
        DBSession.add(p)
        DBSession.commit()
    except:
        DBSession.rollback()
Exemplo n.º 9
0
def setup(context, request):
    #Setup principals
    try:
        p = Principal('group:user')
        p = Principal('group:admin')
        DBSession.add(p)
        DBSession.commit()
    except:
        DBSession.rollback()
Exemplo n.º 10
0
def login(context, request):
    if request.method == "POST":
        form = LoginForm(request.params)
        if form.validate():
            username = form.username.data
            password = form.password.data
            
            u = DBSession.query(User).filter_by(username = username).filter_by(password=hashlib.sha1(password).hexdigest()).first()
            if u:
                request.session['username'] = username
                request.session['principals'] = [a.principal_name for a in u.principals]
                request.session.save()
                return HTTPFound(location='/')
            else:
                return {'form': form, 'error': 'Username or password incorrect'}
            
        else:
            return {'form': form, 'error': None}
    else:
        return {'form': LoginForm(), 'error': None}
Exemplo n.º 11
0
def announce(context, request):
    if request.method == "POST":
        return failure("Invalid request type")
    passkey = request.matchdict['passkey']
    user = DBSession.query(User).filter_by(passkey=passkey).first()
    if not user:
        return failure('Invalid passkey')
    toHex = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x])

    infohash = toHex(request.params.multi['info_hash'])
    peer_id = toHex(request.params.multi['peer_id'])
    torrent = DBSession.query(Torrent).filter_by(info_hash=infohash).first()

    if not torrent:
        return failure("Torrent not found")
    peer = DBSession.query(Peer).filter_by(peer_id = peer_id).first()
    left = int(request.params['left'])
    if not peer:
        peer = Peer()
        peer.user = user
        peer.torrent = torrent
        peer.peer_id = peer_id
        peer.uploaded = 0
        peer.downloaded = 0
        peer.uploaded_total = 0
        peer.downloaded_total = 0
        peer.seeding = False

        
    diff_uploaded = 0
    if 'uploaded' in request.params:
        diff_uploaded = int(request.params['uploaded']) - peer.uploaded
    diff_downloaded = 0
    if 'downloaded' in request.params:
        diff_downloaded = int(request.params['downloaded']) - peer.downloaded
    compactmode = False
    if 'compact' in request.params and request.params['compact'] == '1':
        compactmode=True
    peer.ip = request.environ['REMOTE_ADDR']
    peer.port = int(request.params['port'])
    
    if left == 0:
        peer.seeding = True
        DBSession.add(torrent)
        DBSession.commit()
    else:
        peer.seeding = False
    if 'event' in request.params:
        event = request.params['event']
        if event == 'started':
            peer.active = True
            peer.uploaded = int(request.params['uploaded'])
            peer.downloaded = int(request.params['downloaded'])
            peer.uploaded_total += int(request.params['uploaded'])
            peer.downloaded_total += int(request.params['downloaded'])
            user.uploaded += int(request.params['uploaded'])
            user.downloaded += int(request.params['downloaded'])
        elif event == 'stopped':
            peer.active = False
            peer.uploaded = 0
            peer.downloaded = 0
            peer.uploaded_total += diff_uploaded
            peer.downloaded_total += diff_downloaded
            user.uploaded += diff_uploaded
            user.downloaded += diff_downloaded
        elif event == 'completed':
            peer.seeding = True
            torrent.download_count += 1
            peer.active = True
            peer.uploaded = int(request.params['uploaded'])
            peer.downloaded = int(request.params['downloaded'])
            peer.uploaded_total += diff_uploaded
            peer.downloaded_total += diff_downloaded
            user.uploaded += diff_uploaded
            user.downloaded += diff_downloaded
    else:
        peer.uploaded = int(request.params['uploaded'])
        peer.downloaded = int(request.params['downloaded'])
        peer.uploaded_total += diff_uploaded
        peer.downloaded_total += diff_downloaded
        user.uploaded += diff_uploaded
        user.downloaded += diff_downloaded
    
    if torrent.last_checked == None or (datetime.datetime.now() - torrent.last_checked).seconds >= 60*10:
        peer_objs = torrent.peers
        seeders = 0
        leechers = 0
        for i in peer_objs:
            if i.active:
                if i.seeding:
                    seeders += 1
                else:
                    leechers += 1
        torrent.seeders = seeders
        torrent.leechers = leechers
        torrent.last_checked = datetime.datetime.now()
        DBSession.add(torrent)
    
    DBSession.add(peer)
    DBSession.commit()
    if compactmode:
        peers = ""
        if peer.seeding:
            log.error("peer is seeding")
            peer_objs = DBSession.query(Peer).filter_by(torrent=torrent).filter_by(active=True).filter_by(seeding=False).order_by(func.random()).limit(50).all()
        else:
            peer_objs = DBSession.query(Peer).filter_by(torrent=torrent).filter_by(active=True).filter_by(seeding=True).order_by(func.random()).limit(25).all()+DBSession.query(Peer).filter_by(torrent=torrent).filter_by(active=True).filter_by(seeding=False).order_by(func.random()).limit(25).all()
            log.error(peer_objs)
        for i in peer_objs:
            if i == peer:
                continue
            
            log.error(i.ip)
            ipsplit = i.ip.split(".")
            peers += struct.pack(">BBBBH", int(ipsplit[0]), int(ipsplit[1]),  int(ipsplit[2]), int(ipsplit[3]), i.port)
        log.error(toHex(peers))
        return Response(bencode({'interval': 1800, 'tracker id': 'Hermes', 'complete': torrent.seeders, 'incomplete': torrent.leechers, 'peers': peers}))
    if not 'no_peer_id' in request.params:
        log.error("NOT COMPACT MODE")
        peers = list()
        if peer.seeding:
            peer_objs = DBSession.query(Peer).filter_by(active=True).filter_by(torrent=torrent).filter_by(seeding=False).order_by(func.random()).limit(50).all()
        else:
            peer_objs = DBSession.query(Peer).filter_by(active=True).filter_by(torrent=torrent).filter_by(seeding=True).order_by(func.random()).limit(25).all()+DBSession.query(Peer).filter_by(active=True).filter_by(torrent=torrent).filter_by(seeding=False).order_by(func.random()).limit(25).all()
        for i in peer_objs:
            if i == peer:
                continue
            peers.append({'peer id': i.peer_id, 'ip': i.ip, 'port': i.port})
        log.error(peers)
        return Response(bencode({'interval': 1800, 'tracker id': 'Hermes', 'complete': torrent.seeders, 'incomplete': torrent.leechers, 'peers': peers}))
        
    else:
        log.error("NO_PEER_ID")
Exemplo n.º 12
0
def announce(context, request):
    if request.method == "POST":
        return failure("Invalid request type")
    passkey = request.matchdict['passkey']
    user = DBSession.query(User).filter_by(passkey=passkey).first()
    if not user:
        return failure('Invalid passkey')
    toHex = lambda x: "".join([hex(ord(c))[2:].zfill(2) for c in x])

    infohash = toHex(request.params.multi['info_hash'])
    peer_id = toHex(request.params.multi['peer_id'])
    torrent = DBSession.query(Torrent).filter_by(info_hash=infohash).first()

    if not torrent:
        return failure("Torrent not found")
    peer = DBSession.query(Peer).filter_by(peer_id=peer_id).first()
    left = int(request.params['left'])
    if not peer:
        peer = Peer()
        peer.user = user
        peer.torrent = torrent
        peer.peer_id = peer_id
        peer.uploaded = 0
        peer.downloaded = 0
        peer.uploaded_total = 0
        peer.downloaded_total = 0
        peer.seeding = False

    diff_uploaded = 0
    if 'uploaded' in request.params:
        diff_uploaded = int(request.params['uploaded']) - peer.uploaded
    diff_downloaded = 0
    if 'downloaded' in request.params:
        diff_downloaded = int(request.params['downloaded']) - peer.downloaded
    compactmode = False
    if 'compact' in request.params and request.params['compact'] == '1':
        compactmode = True
    peer.ip = request.environ['REMOTE_ADDR']
    peer.port = int(request.params['port'])

    if left == 0:
        peer.seeding = True
        DBSession.add(torrent)
        DBSession.commit()
    else:
        peer.seeding = False
    if 'event' in request.params:
        event = request.params['event']
        if event == 'started':
            peer.active = True
            peer.uploaded = int(request.params['uploaded'])
            peer.downloaded = int(request.params['downloaded'])
            peer.uploaded_total += int(request.params['uploaded'])
            peer.downloaded_total += int(request.params['downloaded'])
            user.uploaded += int(request.params['uploaded'])
            user.downloaded += int(request.params['downloaded'])
        elif event == 'stopped':
            peer.active = False
            peer.uploaded = 0
            peer.downloaded = 0
            peer.uploaded_total += diff_uploaded
            peer.downloaded_total += diff_downloaded
            user.uploaded += diff_uploaded
            user.downloaded += diff_downloaded
        elif event == 'completed':
            peer.seeding = True
            torrent.download_count += 1
            peer.active = True
            peer.uploaded = int(request.params['uploaded'])
            peer.downloaded = int(request.params['downloaded'])
            peer.uploaded_total += diff_uploaded
            peer.downloaded_total += diff_downloaded
            user.uploaded += diff_uploaded
            user.downloaded += diff_downloaded
    else:
        peer.uploaded = int(request.params['uploaded'])
        peer.downloaded = int(request.params['downloaded'])
        peer.uploaded_total += diff_uploaded
        peer.downloaded_total += diff_downloaded
        user.uploaded += diff_uploaded
        user.downloaded += diff_downloaded

    if torrent.last_checked == None or (
            datetime.datetime.now() - torrent.last_checked).seconds >= 60 * 10:
        peer_objs = torrent.peers
        seeders = 0
        leechers = 0
        for i in peer_objs:
            if i.active:
                if i.seeding:
                    seeders += 1
                else:
                    leechers += 1
        torrent.seeders = seeders
        torrent.leechers = leechers
        torrent.last_checked = datetime.datetime.now()
        DBSession.add(torrent)

    DBSession.add(peer)
    DBSession.commit()
    if compactmode:
        peers = ""
        if peer.seeding:
            log.error("peer is seeding")
            peer_objs = DBSession.query(Peer).filter_by(
                torrent=torrent).filter_by(active=True).filter_by(
                    seeding=False).order_by(func.random()).limit(50).all()
        else:
            peer_objs = DBSession.query(Peer).filter_by(
                torrent=torrent).filter_by(active=True).filter_by(
                    seeding=True).order_by(
                        func.random()).limit(25).all() + DBSession.query(
                            Peer).filter_by(torrent=torrent).filter_by(
                                active=True).filter_by(seeding=False).order_by(
                                    func.random()).limit(25).all()
            log.error(peer_objs)
        for i in peer_objs:
            if i == peer:
                continue

            log.error(i.ip)
            ipsplit = i.ip.split(".")
            peers += struct.pack(">BBBBH", int(ipsplit[0]), int(ipsplit[1]),
                                 int(ipsplit[2]), int(ipsplit[3]), i.port)
        log.error(toHex(peers))
        return Response(
            bencode({
                'interval': 1800,
                'tracker id': 'Hermes',
                'complete': torrent.seeders,
                'incomplete': torrent.leechers,
                'peers': peers
            }))
    if not 'no_peer_id' in request.params:
        log.error("NOT COMPACT MODE")
        peers = list()
        if peer.seeding:
            peer_objs = DBSession.query(Peer).filter_by(active=True).filter_by(
                torrent=torrent).filter_by(seeding=False).order_by(
                    func.random()).limit(50).all()
        else:
            peer_objs = DBSession.query(Peer).filter_by(active=True).filter_by(
                torrent=torrent).filter_by(seeding=True).order_by(func.random(
                )).limit(25).all() + DBSession.query(Peer).filter_by(
                    active=True).filter_by(torrent=torrent).filter_by(
                        seeding=False).order_by(func.random()).limit(25).all()
        for i in peer_objs:
            if i == peer:
                continue
            peers.append({'peer id': i.peer_id, 'ip': i.ip, 'port': i.port})
        log.error(peers)
        return Response(
            bencode({
                'interval': 1800,
                'tracker id': 'Hermes',
                'complete': torrent.seeders,
                'incomplete': torrent.leechers,
                'peers': peers
            }))

    else:
        log.error("NO_PEER_ID")
Exemplo n.º 13
0
def list_torrents(context, request):
    torrents = DBSession.query(Torrent).all()
    return {'torrents': torrents}
Exemplo n.º 14
0
def get_current_user(request):
    u = DBSession.query(User).filter_by(username=request.session['username']).first()
    return u
Exemplo n.º 15
0
def get_principal(name):
    p = DBSession.query(Principal).filter_by(principal_name=name).first()
    return p
Exemplo n.º 16
0
def list_torrents(context, request):
    torrents = DBSession.query(Torrent).all()
    return {'torrents': torrents}
Exemplo n.º 17
0
 def validate_username(form, field):
     log.error("validate_username")
     if not re.match('[a-zA-Z0-9-_]+', field.data):
         raise validators.ValidationError('Username may only contain alpha-numeric characters')
     if DBSession.query(User).filter(func.lower(User.username)==func.lower(field.data)).first():
         raise validators.ValidationError('Username already taken')