Source

tracko / app / models.py

Full commit
import re
from google.appengine.ext import db
from biginteger import BigIntegerProperty


class AppSettings(db.Expando):
  # expected to exist in single instance

  creation_date_utc = db.DateTimeProperty(auto_now_add=True)
  update_date_utc = db.DateTimeProperty(auto_now=True)


class Torrent(db.Model):
  # key_name is hash_info string prefixed with '#'
  
  model_version = db.IntegerProperty(required=True, default=2)
  creation_date_utc = db.DateTimeProperty(auto_now_add=True)
  update_date_utc = db.DateTimeProperty(auto_now=True)
  
  @property
  def info_hash(self):
    return self.key().name()[1:].decode('base64')
  
  @classmethod
  def get_by_info_hash(cls, info_hash):
    return cls.get_by_key_name(cls._encode_key_name(info_hash))
  
  @classmethod
  def get_or_create_by_info_hash(cls, info_hash):
    return cls.get_or_insert(cls._encode_key_name(info_hash))
  
  @classmethod
  def _encode_key_name(cls, info_hash):
    return '#' + info_hash.encode('base64')


class TorrentPeer(db.Model):
  # key_name is peer_id string prefixed with '#'

  model_version = db.IntegerProperty(required=True, default=3)
  torrent = db.ReferenceProperty(
      Torrent, collection_name='peers', required=True)
  address = db.StringProperty(required=True)
  port_number = db.IntegerProperty(required=True)
  n_bytes_left = BigIntegerProperty(required=True, n_bits=1024)
  creation_date_utc = db.DateTimeProperty(auto_now_add=True)
  update_date_utc = db.DateTimeProperty(auto_now=True)

  @property
  def peer_id(self):
    return self.key().name()[1:].decode('base64')

  @classmethod
  def create(cls, peer_id, **kwargs):
    instance = cls(key_name=cls._encode_key_name(peer_id), **kwargs)
    instance.put()
    return instance

  @classmethod
  def get_by_peer_id(cls, peer_id):
    return cls.get_by_key_name(cls._encode_key_name(peer_id))

  @classmethod
  def _encode_key_name(cls, peer_id):
    return '#' + peer_id.encode('base64')