def items_view(short_id): """View item details or show them in the web interface based on Accept-Header or returns 404 if the requested short_id does not exist. -- http://developer.getcloudapp.com/view-item""" db, fs = current_app.db, current_app.fs obj = fs.get(short_id=short_id) if obj is None: abort(404) if request.accept_mimetypes.accept_html: if getattr(obj, 'deleted_at', None): abort(404) if obj.item_type != 'image': # the browser always loads the blob, so we don't want count it twice fs.inc_count(obj._id) if obj.item_type == 'bookmark': return redirect(obj.redirect_url) drop = Drop(obj, current_app.config, urlscheme(request)) if drop.item_type == 'image': return render_template('image.html', drop=drop) elif drop.item_type == 'text': return render_template('text.html', drop=drop) else: return render_template('other.html', drop=drop) return jsonify(Item(obj, current_app.config, urlscheme(request)))
def items_new(): """Generates a new key for the upload process. Timeout after 60 minutes! -- http://developer.getcloudapp.com/upload-file -- http://developer.getcloudapp.com/upload-file-with-specific-privacy""" acc = current_app.db.accounts.find_one( {'email': request.authorization.username}) ParseResult = urlparse(request.url) privacy = 'private' if acc['private_items'] else 'public-read' if not ParseResult.query == '': query = dict( [part.split('=', 1) for part in ParseResult.query.split('&')]) privacy = 'private' if query.get('item[private]', None) else 'public-read' key = current_app.sessions.new(request.authorization.username) res = { "url": urlscheme(request) + '://' + current_app.config['HOSTNAME'], "max_upload_size": current_app.config['MAX_CONTENT_LENGTH'], "params": { "acl": privacy, "key": key }, } return jsonify(res)
def insert(name, redirect_url): acc = db.accounts.find_one({'email': request.authorization.username}) _id = str(getrandbits(32)) retry_count = 1 short_id_length = conf['SHORT_ID_MIN_LENGTH'] while True: short_id = slug(short_id_length) if not db.items.find_one({'short_id': short_id}): break else: retry_count += 1 if retry_count > 3: short_id_length += 1 retry_count = 1 x = { 'account': request.authorization.username, 'name': name, '_id': _id, 'short_id': slug(short_id_length), 'redirect_url': redirect_url, 'item_type': 'bookmark', 'view_counter': 0, 'private': request.form.get('acl', acc['private_items']) if conf['ALLOW_PRIVATE_BOOKMARKS'] else False, 'source': request.headers.get('User-Agent', 'Regenschirm++/1.0').split(' ', 1)[0], 'created_at': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()), 'updated_at': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()), } item = Item(x, conf, urlscheme(request)) db.items.insert(x) items = acc['items'] items.append(_id) db.accounts.update({'_id': acc['_id']}, {'$set': { 'items': items }}, upsert=False) return item
def index(): """Upload a file, when the client has a valid session key. -- http://developer.getcloudapp.com/upload-file""" db, fs = current_app.db, current_app.fs config, sessions = current_app.config, current_app.sessions if request.method == 'POST' and not request.accept_mimetypes.accept_html: try: account = sessions.pop(request.form.get('key'))['account'] except KeyError: abort(401) acc = db.accounts.find_one({'email': account}) source = request.headers.get('User-Agent', 'Regenschirm++/1.0').split(' ', 1)[0] privacy = request.form.get('acl', acc['private_items']) _id = fs.upload_file(config, account, request.files.get('file'), source, privacy) items = acc['items'] items.append(_id) db.accounts.update({'_id': acc['_id']}, {'$set': { 'items': items }}, upsert=False) obj = fs.get(_id) if obj is None: abort(400) else: return jsonify(Item(obj, config, urlscheme(request))) else: users = db.accounts.find().count() files = fs.gfs._GridFS__files.count() size = sum([f['length'] for f in fs.gfs._GridFS__files.find()]) hits = sum([f['view_counter'] for f in fs.mdb.find()]) if request.args.get('format') == 'csv': fields = [('users', users), ('files', files), ('size', size), ('hits', hits)] return Response('\n'.join('%s,%s' % field for field in fields), 200) return Response(render_template("index.html", **locals()), 200, content_type="text/html")
def items(): """Show items from user. Optional query parameters: - page (int) - default: 1 - per_page (int) - default: 5 - type (str) - default: None, filter by image, bookmark, text, archive, audio, video, or unknown - deleted (bool) - default: False, show trashed items -- http://developer.getcloudapp.com/list-items""" db, fs = current_app.db, current_app.fs ParseResult = urlparse(request.url) params = { 'per_page': '5', 'page': '1', 'type': None, 'deleted': False, 'source': None } if not ParseResult.query == '': query = dict( [part.split('=', 1) for part in ParseResult.query.split('&')]) params.update(query) listing = [] try: pp = int(params['per_page']) page = int(params['page']) email = request.authorization.username except (ValueError, KeyError): abort(400) query = {'account': email} if params['type'] != None: query['item_type'] = params['type'] if params['deleted'] == False: query['deleted_at'] = None if params['source'] != None: query['source'] = {'$regex': '^' + unquote(params['source'])} items = db.items.find(query) for item in items.sort('updated_at', DESCENDING)[pp * (page - 1):pp * page]: listing.append( Item(fs.get(_id=item['_id']), current_app.config, urlscheme(request))) return json.dumps(listing[::-1])
def index(): """Upload a file, when the client has a valid session key. -- http://developer.getcloudapp.com/upload-file""" db, fs = current_app.db, current_app.fs config, sessions = current_app.config, current_app.sessions if request.method == 'POST' and not request.accept_mimetypes.accept_html: try: account = sessions.pop(request.form.get('key'))['account'] except KeyError: abort(401) acc = db.accounts.find_one({'email': account}) source = request.headers.get('User-Agent', 'Regenschirm++/1.0').split(' ', 1)[0] privacy = request.form.get('acl', acc['private_items']) _id = fs.upload_file(config, account, request.files.get('file'), source, privacy) items = acc['items'] items.append(_id) db.accounts.update({'_id': acc['_id']}, {'$set': {'items': items}}, upsert=False) obj = fs.get(_id) if obj is None: abort(400) else: return jsonify(Item(obj, config, urlscheme(request))) else: users = db.accounts.find().count() files = fs.gfs._GridFS__files.count() size = sum([f['length'] for f in fs.gfs._GridFS__files.find()]) hits = sum([f['view_counter'] for f in fs.mdb.find()]) if request.args.get('format') == 'csv': fields = [('users', users), ('files', files), ('size', size), ('hits', hits)] return Response('\n'.join('%s,%s' % field for field in fields), 200) return Response(render_template("index.html", **locals()), 200, content_type="text/html")
def items(): """Show items from user. Optional query parameters: - page (int) - default: 1 - per_page (int) - default: 5 - type (str) - default: None, filter by image, bookmark, text, archive, audio, video, or unknown - deleted (bool) - default: False, show trashed items -- http://developer.getcloudapp.com/list-items""" db, fs = current_app.db, current_app.fs ParseResult = urlparse(request.url) params = {'per_page': '5', 'page': '1', 'type': None, 'deleted': False, 'source': None} if not ParseResult.query == '': query = dict([part.split('=', 1) for part in ParseResult.query.split('&')]) params.update(query) listing = [] try: pp = int(params['per_page']) page = int(params['page']) email = request.authorization.username except (ValueError, KeyError): abort(400) query = {'account': email} if params['type'] != None: query['item_type'] = params['type'] if params['deleted'] == False: query['deleted_at'] = None if params['source'] != None: query['source'] = {'$regex': '^' + unquote(params['source'])} items = db.items.find(query) for item in items.sort('updated_at', DESCENDING)[pp*(page-1):pp*page]: listing.append(Item(fs.get(_id=item['_id']), current_app.config, urlscheme(request))) return json.dumps(listing[::-1])
def insert(name, redirect_url): acc = db.accounts.find_one({'email': request.authorization.username}) _id = str(getrandbits(32)) retry_count = 1 short_id_length = conf['SHORT_ID_MIN_LENGTH'] while True: short_id = slug(short_id_length) if not db.items.find_one({'short_id': short_id}): break else: retry_count += 1 if retry_count > 3: short_id_length += 1 retry_count = 1 x = { 'account': request.authorization.username, 'name': name, '_id': _id, 'short_id': slug(short_id_length), 'redirect_url': redirect_url, 'item_type': 'bookmark', 'view_counter': 0, 'private': request.form.get('acl', acc['private_items']) if conf['ALLOW_PRIVATE_BOOKMARKS'] else False, 'source': request.headers.get('User-Agent', 'Regenschirm++/1.0').split(' ', 1)[0], 'created_at': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()), 'updated_at': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()), } item = Item(x, conf, urlscheme(request)) db.items.insert(x) items = acc['items'] items.append(_id) db.accounts.update({'_id': acc['_id']}, {'$set': {'items': items}}, upsert=False) return item
def items_edit(object_id): """rename/delete/change privacy of an item. -- http://developer.getcloudapp.com/rename-item -- http://developer.getcloudapp.com/delete-item -- http://developer.getcloudapp.com/change-security-of-item""" conf, db, fs = current_app.config, current_app.db, current_app.fs item = db.items.find_one({ 'account': request.authorization.username, '_id': object_id }) if not item: abort(404) if request.method == 'DELETE': item['deleted_at'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) elif request.method == 'PUT': try: data = json.loads(request.data)['item'] key, value = data.items()[0] if not key in ['private', 'name', 'deleted_at']: raise ValueError except ValueError: return ('Unprocessable Entity', 422) if key == 'name' and item['item_type'] != 'bookmark': item['filename'] = value elif key == 'private' and item['item_type'] == 'bookmark' and value \ and not conf['ALLOW_PRIVATE_BOOKMARKS']: pass else: item[key] = value item['updated_at'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) db.items.save(item) item = fs.get(item['_id']) return jsonify(Item(item, conf, urlscheme(request)))
def items_edit(object_id): """rename/delete/change privacy of an item. -- http://developer.getcloudapp.com/rename-item -- http://developer.getcloudapp.com/delete-item -- http://developer.getcloudapp.com/change-security-of-item""" conf, db, fs = current_app.config, current_app.db, current_app.fs item = db.items.find_one({'account': request.authorization.username, '_id': object_id}) if not item: abort(404) if request.method == 'DELETE': item['deleted_at'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) elif request.method == 'PUT': try: data = json.loads(request.data)['item'] key, value = data.items()[0] if not key in ['private', 'name', 'deleted_at']: raise ValueError except ValueError: return ('Unprocessable Entity', 422) if key == 'name' and item['item_type'] != 'bookmark': item['filename'] = value elif key == 'private' and item['item_type'] == 'bookmark' and value \ and not conf['ALLOW_PRIVATE_BOOKMARKS']: pass else: item[key] = value item['updated_at'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()) db.items.save(item) item = fs.get(item['_id']) return jsonify(Item(item, conf, urlscheme(request)))
def items_new(): """Generates a new key for the upload process. Timeout after 60 minutes! -- http://developer.getcloudapp.com/upload-file -- http://developer.getcloudapp.com/upload-file-with-specific-privacy""" acc = current_app.db.accounts.find_one({'email': request.authorization.username}) ParseResult = urlparse(request.url) privacy = 'private' if acc['private_items'] else 'public-read' if not ParseResult.query == '': query = dict([part.split('=', 1) for part in ParseResult.query.split('&')]) privacy = 'private' if query.get('item[private]', None) else 'public-read' key = current_app.sessions.new(request.authorization.username) res = { "url": urlscheme(request) + '://' + current_app.config['HOSTNAME'], "max_upload_size": current_app.config['MAX_CONTENT_LENGTH'], "params": { "acl": privacy, "key": key }, } return jsonify(res)