Пример #1
0
 def __init__(self, request, response):
     ApiHandler.__init__(self, request, response)
     qs = parse_qs(self.request.query_string)
     try:
         qtype = qs['type'][0]
     except (IndexError, KeyError, ):
         qtype = 'open'
     self.open = qtype in ('open', 'all')
     self.closed = qtype in ('closed', 'all')
Пример #2
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tf2auctions.lib import ApiHandler
from tf2auctions.models.counters import get_counter


class Stats(ApiHandler):
    keys = ('bids', 'bid_items', 'listings', 'listing_items', 'players')

    def get(self):
	stats = [(k, get_counter(k)) for k in self.keys]
	self.write_json(dict(stats))


main = ApiHandler.make_main(Stats)


if __name__ == '__main__':
    main()
Пример #3
0
	    data = self.body_json()
	    items = data['items']
	    item_ids = [(i['id'], i) for i in items]
	    if len(item_ids) != len(items):
		raise TypeError('Missing item identifiers.')
	    desc = data['desc'][0:400]
	    days = data['days'] + 0 # force exception
	    if days < 0 or days > 30:
		raise TypeError('Invalid duration.')
	    min_bid = [b+0 for b in data['min_bid']] # again, force an exception
	    key = Listing.build(item_ids=item_ids, desc=desc, days=days, min_bid=min_bid,
				bid_currency_use=data.get('bid_currency_use'),
				bid_currency_start=data.get('bid_currency_start'),
				bid_currency_type=data.get('bid_currency_type'),
				feature_listing=data.get('feature_listing'))
	except (Exception, ), exc:
	    error('add listing: %s', exc)
	    self.error(500)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = {'msg':'success', 'key':key.id()}
	return self.write_json(result)


main = ApiHandler.make_main(AddListing)


if __name__ == '__main__':
    main()
Пример #4
0
		target = bid.owner
	    elif source == 'bidder':
		## bidder is adding feedback for lister; target is listing owner
		target = listing.owner
	    else:
		raise TypeError('Invalid feedback source')
	    source = user_steam_id(user)
            if fb:
		#raise TypeError('Feedback exists')
                fb.rating = rating
                fb.comment = text
                fb.put()
            else:
                fb = Feedback.build(bid, listing, source, target, rating, text)
	except (Exception, ), exc:
	    self.error(500)
	    raise
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = fb.encode_builtin()
	return self.write_json(result)


main = ApiHandler.make_main(SaveFeedback)


if __name__ == '__main__':
    main()

Пример #5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tf2auctions.lib import ApiHandler
from tf2auctions.models.blog import BlogEntry


class BlogEntries(ApiHandler):
    def get(self):
	entries = BlogEntry.recent(limit=10)
	entries = [entry.encode_builtin() for entry in entries]
	self.write_json(entries)


main = ApiHandler.make_main(BlogEntries)


if __name__ == '__main__':
    main()
Пример #6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tf2auctions.lib import ApiHandler, search_id64
from tf2auctions.models import PlayerProfile


class Profile(ApiHandler):
    def get(self):
	name = self.path_tail()
	try:
	    profile = PlayerProfile.get_by_id64(search_id64(name))
	except (Exception, ), exc:
	    profile = PlayerProfile.get_by_name(name)
	if not profile:
	    self.error(404)
	else:
	    profile.refresh()
	    self.write_json(profile.encode_builtin())


main = ApiHandler.make_main(Profile)


if __name__ == '__main__':
    main()
def send(body):
    mail.send_mail(
        sender="*****@*****.**",
        to="*****@*****.**",
        subject="New Listing Cross Post",
        body=""" %s """ % (body,),
    )


class CrossPostListing(ApiHandler):
    """ CrossPostListing -> cross post a listing to some other sites
        via email.

    """

    def post(self):
        """ Called by the task queue API when a this task is ready to
	    run.  The tasks are created by the Listing model.
	"""
        listing = Listing.get(self.request.get("listing_key"))
        summary = {"listing": {"id": listing.key().id()}}
        send(body=json_dumps(summary))


main = ApiHandler.make_main(CrossPostListing)


if __name__ == "__main__":
    main()
Пример #8
0
class CurrentUserProfile(ApiHandler):
    def get(self):
	try:
	    user = users.get_current_user()
	    if not user:
		self.error(401)
		return
	    profile = PlayerProfile.get_by_user(user)
	    if not profile:
		self.error(401)
		return
	    profile.refresh()
	    qs = parse_qs(self.request.query_string)
	    self.write_json(
		profile.encode_builtin(
		    settings='settings' in qs,
		    complete='complete' in qs,
		)
	    )
	except (Exception, ), exc:
	    self.error(500)
	    self.write_json({'exception':str(exc)})


main = ApiHandler.make_main(CurrentUserProfile)


if __name__ == '__main__':
    main()
Пример #9
0
        body=body_template % locals(),
    )


class NotifyBid(ApiHandler):
    def post(self):
	try:
	    key = self.request.get('bid')
	    update = self.request.get('update')
	    #warn('notify bid: %s, %s', key, update)
	    bid = Bid.get(key)
	    listing = bid.listing
	    profile = listing.owner_profile()
	    settings = PlayerSettings.get_by_id64(listing.owner).encode_builtin(complete=True)
	    if settings['email'] and settings['notify-bids']:
		name = getattr(profile, 'personaname', listing.owner)
		send(name, settings['email'], listing.owner, listing.url())

	except (Exception, ), exc:
	    warn('notify bid exception: %s', exc)
	    self.response.out.write('WARN')
	else:
	    self.response.out.write('OK')


main = ApiHandler.make_main(NotifyBid)


if __name__ == '__main__':
    main()
Пример #10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from logging import error, warn

from tf2auctions.lib import ApiHandler
from tf2auctions.models import Listing


class EndListing(ApiHandler):
    def post(self):
	try:
	    key = self.request.get('key')
	    warn('end listing: %s', key)
	    listing = Listing.get(key)
	    if listing:
		listing.end('Ended by system.')
	except (Exception, ), exc:
	    error('expire listing exception: %s', exc)
	    self.response.out.write('ERROR')
	else:
	    self.response.out.write('OK')


main = ApiHandler.make_main(EndListing)


if __name__ == '__main__':
    main()
Пример #11
0
	    taskqueue.add(
		url='/api/v1/admin/queue/reverify-items',
		queue_name='item-verification',
		eta=eta_call(1),
		params=params)

    def reverify(self, cls, key):
	""" Verify item ownership against the owner's backpack.

	This method will return the object if ownership is correct,
	otherwise it will cancel the listing or bid.
	"""
	kind = cls.__name__.lower()
	obj = cls.get(key)
	info('re-verify items in %s: %s', kind, key)
	items = obj.items()
	profile = PlayerProfile.get_by_user(user_steam_id(obj.owner))
	profile.refresh()
	#warn('re-verify items: %s', [long(i.uniqueid) for i in items])
	if profile.owns_all([long(i.uniqueid) for i in items]):
	    return obj
	else:
	    obj.cancel('Item ownership changed (%s)' % (kind, ))


main = ApiHandler.make_main(ReverifyItems)


if __name__ == '__main__':
    main()
Пример #12
0
	if bookmark:
	    q.filter('__key__ >', db.Key(bookmark))
	subscription = q.get()

	## 0. done if there are no more subscriptions
	if not subscription:
	    return

	## 1. otherwise, process this subscription via its settings:
	listing_key = self.request.get('listing_key')
	listing = Listing.get(listing_key)
	settings = subscription.settings
	if settings.email and settings.notify_listing_defs:
	    items = [i.defindex for i in listing.items()]
	    for defindex in items:
		if defindex in settings.notify_listing_defs:
		    ## no name, that would mean yet another datastore read...
		    send(settings.email, listing.url())
		    break

	## 2.  add another item to the queue:
	queue_tool.notify_listing(subscription_key=subscription.key(),
				  listing_key=listing_key)


main = ApiHandler.make_main(NotifyListing)


if __name__ == '__main__':
    main()
Пример #13
0
from tf2auctions.models.support import Issues


class IssuesList(ApiHandler):
    def __init__(self, request, response):
        ApiHandler.__init__(self, request, response)
        qs = parse_qs(self.request.query_string)
        try:
            qtype = qs['type'][0]
        except (IndexError, KeyError, ):
            qtype = 'open'
        self.open = qtype in ('open', 'all')
        self.closed = qtype in ('closed', 'all')

    def get(self):
	self.write_json(self.data())

    def cache_key(self):
        return 'issues-%s-%s' % (self.open, self.closed, )

    @cache(lambda self:self.cache_key(), ttl=60*10, always=True)
    def data(self):
        return Issues().list(open=self.open, closed=self.closed)


main = ApiHandler.make_main(IssuesList)


if __name__ == '__main__':
    main()
Пример #14
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.api import users

from tf2auctions.lib import ApiHandler
from tf2auctions.models import Feedback


class ProfileFeedback(ApiHandler):
    def get(self):
        fbs = Feedback.get_by_target(self.path_tail())
        if not fbs:
            self.error(404)
            return
        self.write_json([fb.encode_builtin() for fb in fbs])


main = ApiHandler.make_main(ProfileFeedback)


if __name__ == "__main__":
    main()
Пример #15
0
class ChooseWinner(ApiHandler):
    def post(self):
	try:
	    post = self.body_json()
	    listing_id = int(post['id'])
	    listing = Listing.get_by_id(listing_id)
	    if not listing:
		self.error(404)
		return
	    bid = post['bid']
	    current_user = users.get_current_user()
	    if current_user and (listing.owner == user_steam_id(current_user.nickname())):
		db_result = listing.winner(bid)
	    else:
		self.error(401)
		return
	    result = {'msg':'okay', 'result':db_result}
	except (Exception, ), exc:
	    self.error(500)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	return self.write_json(result)


main = ApiHandler.make_main(ChooseWinner)


if __name__ == '__main__':
    main()
Пример #16
0
from tf2auctions.models.support import ChangeLogFile


class ChangeLog(ApiHandler):
    def get(self):
	self.response.out.write(self.data())

    @cache(lambda self:'changelog', ttl=60*10, always=True)
    def data(self):
        branch = tag = None
        if features.devel:
            branch = 'master'
        else:
            tag = features.version

        if features.local_static_files:
            from os import path
            from tf2auctions.ext.markdown import markdown
            logfile = open(path.join(features.app_dir, 'CHANGES.md'))
            log = markdown(logfile.read())
        else:
            log = ChangeLogFile(tag=tag, branch=branch).read()
        return log


main = ApiHandler.make_main(ChangeLog)


if __name__ == '__main__':
    main()
Пример #17
0
from tf2auctions.models.support import ToDoFile


class ToDo(ApiHandler):
    def get(self):
	self.response.out.write(self.data())

    @cache(lambda self:'todo', ttl=60*10, always=True)
    def data(self):
        branch = tag = None
        if features.devel:
            branch = 'master'
        else:
            tag = features.version

        if features.local_static_files:
            from os import path
            from tf2auctions.ext.markdown import markdown
            logfile = open(path.join(features.app_dir, 'TODO.md'))
            log = markdown(logfile.read())
        else:
            log = ToDoFile(tag=tag, branch=branch).read()
        return log


main = ApiHandler.make_main(ToDo)


if __name__ == '__main__':
    main()
Пример #18
0
            if not listing:
                self.error(404)
                return
            current_user = users.get_current_user()
            if current_user and (listing.owner == user_steam_id(current_user.nickname())):
                db_result = listing.cancel("Cancelled by user.")
            else:
                import logging

                logging.warn(
                    "wtf %s %s %s",
                    user_steam_id(current_user.nickname()),
                    listing.owner,
                    current_user.nickname() == listing.owner,
                )
                self.error(401)
                return
            result = {"msg": "okay", "result": db_result}
        except (Exception,), exc:
            self.error(500)
            exc = exc.message if hasattr(exc, "message") else str(exc)
            result = {"msg": "error", "description": exc}
        return self.write_json(result)


main = ApiHandler.make_main(CancelListing)


if __name__ == "__main__":
    main()
Пример #19
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.api import users

from tf2auctions.lib import ApiHandler
from tf2auctions.models import Listing


class ListingDetail(ApiHandler):
    def get(self):
	listing_id = int(self.path_tail())
	listing = Listing.get_by_id(listing_id)
	if not listing:
	    self.error(404)
	    return
	self.write_json(listing.encode_builtin(bids=True))


main = ApiHandler.make_main(ListingDetail)


if __name__ == '__main__':
    main()
Пример #20
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from logging import error
from google.appengine.api import users

from tf2auctions.lib import ApiHandler
from tf2auctions.models.message import PlayerMessage


class RemoveMessage(ApiHandler):
    def post(self):
	try:
	    key = self.body_json()['key']
	    PlayerMessage.remove(key, users.get_current_user())
	except (Exception, ), exc:
	    self.error(500)
	    error('remove message: %s', exc)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = {'msg':'success'}
	return self.write_json(result)


main = ApiHandler.make_main(RemoveMessage)


if __name__ == '__main__':
    main()
Пример #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tf2auctions.lib import ApiHandler
from tf2auctions.models.faq import get_all_decoded


class Faq(ApiHandler):
    def get(self):
	self.write_json( get_all_decoded() )


main = ApiHandler.make_main(Faq)


if __name__ == '__main__':
    main()
Пример #22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from logging import error, warn

from tf2auctions.lib import ApiHandler
from tf2auctions.models import Listing


class ExpireListing(ApiHandler):
    def post(self):
	try:
	    key = self.request.get('key')
	    warn('expire listing: %s', key)
	    listing = Listing.get(key)
	    if listing:
		listing.expire('Expired by system.')
	except (Exception, ), exc:
	    error('expire listing exception: %s', exc)
	    self.response.out.write('ERROR')
	else:
	    self.response.out.write('OK')


main = ApiHandler.make_main(ExpireListing)


if __name__ == '__main__':
    main()
Пример #23
0
	sender='TF2Auctions.com Notification Bot <*****@*****.**>',
	to=email,
	subject='Your Bid Won on TF2Auctions.com',
        body=body_template % locals(),
    )


class NotifyWin(ApiHandler):
    def post(self):
	try:
	    key = self.request.get('bid')
	    warn('notify win: %s', key)
	    bid = Bid.get(key)
	    profile = bid.owner_profile()
	    settings = PlayerSettings.get_by_id64(bid.owner).encode_builtin(complete=True)
	    if settings['email'] and settings['notify-wins']:
		name = getattr(profile, 'personaname', bid.owner)
		send(name, settings['email'], bid.owner, bid.listing.url())
	except (Exception, ), exc:
	    warn('notify win exception: %s', exc)
	    self.response.out.write('WARN')
	else:
	    self.response.out.write('OK')


main = ApiHandler.make_main(NotifyWin)


if __name__ == '__main__':
    main()
Пример #24
0
from logging import error
from google.appengine.api import users

from tf2auctions.lib import ApiHandler
from tf2auctions.models.message import PlayerMessage


class LeaveMessage(ApiHandler):
    def post(self):
	try:
	    source = users.get_current_user()
	    if not source:
		self.error(401)
		return
	    payload = self.body_json()
	    msg = PlayerMessage.build(source,
				      payload['target'],
				      payload['message'][0:400])
	    self.write_json({'msg':'success'})
	except (Exception, ), exc:
	    error('leave message: %s', exc)
	    self.error(500)
	    self.write_json({'exception':str(exc)})


main = ApiHandler.make_main(LeaveMessage)


if __name__ == '__main__':
    main()
Пример #25
0
		    item_ids=item_ids,
                    public_msg=public_msg,
                    private_msg=private_msg,
		    listing_id=bid['id'],
                    currency_val=currency_val)
	    else:
		key = Bid.build(
		    item_ids=item_ids,
                    public_msg=public_msg,
                    private_msg=private_msg,
		    listing_id=bid['id'],
                    currency_val=currency_val
                    )
	except (Exception, ), exc:
            raise
	    error('add bid: %s', exc)
	    self.error(500)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = {'msg':'success', 'key':key.id()}
	return self.write_json(result)


main = ApiHandler.make_main(AddBid)


if __name__ == '__main__':
    main()

Пример #26
0
"""


def send(name, email, id64, message):
    mail.send_mail(
	sender='TF2Auctions.com Support <*****@*****.**>',
	to='*****@*****.**',
	subject='Message from Site Visitor',
        body=body_template % locals(),
    )


class SendFeedback(ApiHandler):
    def post(self):
	data = self.body_json()
	msg = data.get('msg')
	if msg:
	    send(data.get('name'),
		 data.get('email'),
		 data.get('id64'),
		 msg[0:2048])
	self.write_json({})


main = ApiHandler.make_main(SendFeedback)


if __name__ == '__main__':
    main()
Пример #27
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from logging import error
from google.appengine.api import users

from tf2auctions.lib import ApiHandler
from tf2auctions.models.settings import PlayerSettings


class SaveSettings(ApiHandler):
    def post(self):
	try:
	    user = users.get_current_user()
	    settings = self.body_json()
	    PlayerSettings.put_merged(user, settings)
	except (Exception, ), exc:
	    self.error(500)
	    error('save settings: %s', exc)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = {'msg':'success'}
	return self.write_json(result)


main = ApiHandler.make_main(SaveSettings)


if __name__ == '__main__':
    main()
Пример #28
0
from logging import error, warn
from google.appengine.api import users

from tf2auctions.lib import ApiHandler, user_steam_id
from tf2auctions.models import Bid


class CancelBid(ApiHandler):
    def post(self):
	try:
	    key = self.body_json()['key']
	    bid = Bid.get(key)
	    if not bid:
		self.error(404)
	    elif user_steam_id(users.get_current_user()) != bid.owner:
		self.error(401)
	    else:
		bid.cancel()
	except (Exception, ), exc:
	    self.error(500)
            raise
	    error('cancel bid exception: %s', exc)
	return self.write_json({})


main = ApiHandler.make_main(CancelBid)


if __name__ == '__main__':
    main()
Пример #29
0
from google.appengine.api import users

from tf2auctions.lib import ApiHandler, user_steam_id
from tf2auctions.models import Bid


class PlayerBids(ApiHandler):
    def get(self):
	try:
	    id64 = self.path_tail()

	    q = Bid.all()
	    q.filter('owner = ', id64)
	    qs = parse_qs(self.request.query_string)
	    #if (user_steam_id(users.get_current_user()) == id64) and 'ext' in qs:
            if not 'ext' in qs:
		q.filter('status = ', 'active')
	    q.order('-created')
	    rs = [r.encode_builtin() for r in q.fetch(limit=100)]
	    self.write_json(rs)
	except (Exception, ), exc:
	    self.error(500)
	    self.write_json({'exception':str(exc)})


main = ApiHandler.make_main(PlayerBids)


if __name__ == '__main__':
    main()
Пример #30
0
# -*- coding: utf-8 -*-
from google.appengine.api import users

from tf2auctions.lib import ApiHandler, user_steam_id
from tf2auctions.models.message import PlayerMessage


class FetchMessages(ApiHandler):
    def get(self):
	try:
	    user = users.get_current_user()
	    msgs = PlayerMessage.get_for_user(user)
	except (Exception, ), exc:
	    self.error(500)
	    exc = exc.message if hasattr(exc, 'message') else str(exc)
	    result = {'msg':'error', 'description':exc}
	else:
	    result = {
		'messages' : [msg.encode_builtin() for msg in msgs],
		'full' : len(msgs) >= 100,
	    }
	return self.write_json(result)


main = ApiHandler.make_main(FetchMessages)


if __name__ == '__main__':
    main()