def do_create_screenshot(user: User, package: Package, title: str, file, reason: str = None): thirty_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=30) count = package.screenshots.filter(PackageScreenshot.created_at > thirty_minutes_ago).count() if count >= 20: raise LogicError(429, "Too many requests, please wait before trying again") uploaded_url, uploaded_path = upload_file(file, "image", "a PNG or JPG image file") counter = 1 for screenshot in package.screenshots.all(): screenshot.order = counter counter += 1 ss = PackageScreenshot() ss.package = package ss.title = title or "Untitled" ss.url = uploaded_url ss.approved = package.checkPerm(user, Permission.APPROVE_SCREENSHOT) ss.order = counter db.session.add(ss) if reason is None: msg = "Created screenshot {}".format(ss.title) else: msg = "Created screenshot {} ({})".format(ss.title, reason) addNotification(package.maintainers, user, NotificationType.PACKAGE_EDIT, msg, package.getURL("packages.view"), package) addAuditLog(AuditSeverity.NORMAL, user, msg, package.getURL("packages.view"), package) db.session.commit() return ss
def post(self): form = CreatePackageForm() packages = Package.query.order_by(Package.id.desc()).all() if form.validate_on_submit(): try: # Create database entry p = Package() p.name = form.name.data or None p.description = form.description.data or None p.price = form.price.data or None p.slots = form.slots.data or None p.duration = form.duration.data or None p.order = form.order.data or 0 p.active = False db.session.add(p) db.session.commit() return redirect('/admin/packages/') except: import traceback db.session.rollback() traceback.print_exc() return redirect('/admin/packages/') return render_template('admin/packages.html', form=form, packages=packages)
def create_repo(): '''Create repositories.''' base = app.config['REPO_PATH'] releases = app.config['DEFAULT_RELEASES'] for release in releases: for arch in app.config['REPO_ARCH']: spath = os.path.join(base, app.config['REPO_TESTING_DIR'], release[1:], arch) tpath = os.path.join(base, app.config['REPO_STABLE_DIR'], release[1:], arch) Package.create_repo([spath, tpath])
def new_package(): form = ShippingForm() if form.validate_on_submit(): data = form.data new_package = Package(name=data["name_sender"], recipient=data["name_recipient"], origin=data["origin"], destination=data["destination"], location=data["origin"]) db.session.add(new_package) db.session.commit() Package.advance_all_locations() return redirect("/") return render_template('shipping_request.html', form=form)
def get_package_tabs(user: User, package: Package): if package is None or not package.checkPerm(user, Permission.EDIT_PACKAGE): return [] return [{ "id": "edit", "title": "Edit Details", "url": package.getURL("packages.create_edit") }, { "id": "releases", "title": "Releases", "url": package.getURL("packages.list_releases") }, { "id": "screenshots", "title": "Screenshots", "url": package.getURL("packages.screenshots") }, { "id": "maintainers", "title": "Maintainers", "url": package.getURL("packages.edit_maintainers") }, { "id": "audit", "title": "Audit Log", "url": package.getURL("packages.audit") }, { "id": "share", "title": "Share and Badges", "url": package.getURL("packages.share") }, { "id": "remove", "title": "Remove", "url": package.getURL("packages.remove") }]
def shipping_request(): form = ShippingForm() if form.validate_on_submit(): data = form.data new_package = Package(sender=data["sender_name"], recipient=data["recipient_name"], origin=data["origin"], destination=data["destination"], location=data["origin"]) db.session.add(new_package) db.session.commit() Package.advance_all_locations() return redirect(url_for('.index')) return render_template("shipping_request.html", form=form)
def new_package(): form = Shipping_Form() if (form.validate_on_submit()): data = form.data new_package = Package(sender=data["sender"], recipient=data['recipient'], origin=data['origin'], destination=data['destination'], location=data['origin']) db.session.add(new_package) db.session.commit() Package.advance_all_locations() return redirect('/') return render_template('shipping_request.html', form=form)
def do_create_vcs_release(user: User, package: Package, title: str, ref: str, min_v: MinetestRelease = None, max_v: MinetestRelease = None, reason: str = None): check_can_create_release(user, package) rel = PackageRelease() rel.package = package rel.title = title rel.url = "" rel.task_id = uuid() rel.min_rel = min_v rel.max_rel = max_v db.session.add(rel) if reason is None: msg = "Created release {}".format(rel.title) else: msg = "Created release {} ({})".format(rel.title, reason) addAuditLog(AuditSeverity.NORMAL, user, msg, package.getURL("packages.view"), package) db.session.commit() makeVCSRelease.apply_async((rel.id, nonEmptyOrNone(ref)), task_id=rel.task_id) return rel
def form(): form = ShippingForm() if form.validate_on_submit(): data = form.data new_package = Package(sender=data["sender_name"], recipient=data["recipient_name"], origin=data["origin"], destination=data["destination"], location=data["origin"]) db.session.add(new_package) db.session.commit() # DEBUG: Advance Time Package.advance_all_locations() return redirect('/') return render_template('shipping_request.html', form=form)
def create_package(cls, price=1000, available_packages=10): """Return an instance of the Package class.""" package = Package( name="Social Media Package", price=price, audience="50-100", available_packages=available_packages, package_type="Cash", ) return package
def package(): form = ShippingForm() if form.validate_on_submit(): package = Package() form.populate_obj(package) package.location = package.origin package.save() Package.advance_all_locations() return redirect(url_for('.index')) return render_template('shipping_request.html', form=form)
def check_can_create_release(user: User, package: Package): if not package.checkPerm(user, Permission.MAKE_RELEASE): raise LogicError(403, "You do not have permission to make releases") five_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=5) count = package.releases.filter( PackageRelease.releaseDate > five_minutes_ago).count() if count >= 5: raise LogicError( 429, "You've created too many releases for this package in the last 5 minutes, please wait before trying again" )
def new_package(): form = ShippingForm() form.origin.choices = [(city, city) for city in map.keys()] form.destination.choices = [(city, city) for city in map.keys()] if form.validate_on_submit(): Package.advance_all_locations() print(form.data) data = form.data new_package = Package( sender=data["sender_name"], recipient=data["recipient_name"], origin=data["origin"], destination=data["destination"], location=data["origin"] ) db.session.add(new_package) db.session.commit() return redirect(url_for(".index")) return render_template('shipping_request.html', form=form)
def api_edit_package(token: APIToken, package: Package, data: dict, reason: str = "API"): if not token.canOperateOnPackage(package): error(403, "API token does not have access to the package") reason += ", token=" + token.name package = guard(do_edit_package)(token.owner, package, False, data, reason) return jsonify({ "success": True, "package": package.getAsDictionary(current_app.config["BASE_URL"]) })
def new_package(): form = ShippingForm() if request.method == 'POST': package = Package(sender=form.sender.data, recipient=form.recipient.data, origin=form.origin.data, destination=form.destination.data, express_shipping=form.express_shipping.data) db.session.add(package) db.session.commit() return redirect(url_for('.root_endpoint')) return render_template('shipping_request.html', form=form)
def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() data = loads(self.data) print "Received from '%s': %s \n" % (self.client_address[0], data) list_packages = "" for package in data['packages']: if list_packages == "": list_packages += package else: list_packages += " " + package print(list_packages) # just send back the same data, but upper-cased self.request.sendall(dumps({'return': data['packages']})) try: obj = Package.objects.filter(title=data['hostname']).update(ip=data['ip'],packages=list_packages,slug=data['hostname']) if obj: self.request.sendall(dumps({'return':'Successfully updated'})) else: obj = Package(title=data['hostname'],ip=data['ip'],packages=list_packages,slug=data['hostname']) obj.save() self.request.sendall(dumps({'return':'Successfully created'})) except Package.DoesNotExist: obj = Package(title=data['hostname'],ip=data['ip'],packages=list_packages,slug=data['hostname']) obj.save() self.request.sendall(dumps({'return':'Successfully created'}))
def package(): form = ShipForm() if form.validate_on_submit(): data = form.data new_package = Package(sender=data["name"], recipient=data["recipient"], origin=data["origin"], destination=data["destination"], location=data["origin"]) db.session.add(new_package) db.session.commit() return redirect("/") return render_template("shipping_request.html", form=form)
def delete_screenshot(token: APIToken, package: Package, id: int): ss = PackageScreenshot.query.get(id) if ss is None or ss.package != package: error(404, "Screenshot not found") if not token: error(401, "Authentication needed") if not package.checkPerm(token.owner, Permission.ADD_SCREENSHOTS): error(403, "You do not have the permission to delete screenshots") if not token.canOperateOnPackage(package): error(403, "API token does not have access to the package") if package.cover_image == ss: package.cover_image = None db.session.merge(package) db.session.delete(ss) db.session.commit() return jsonify({"success": True})
def order_screenshots(token: APIToken, package: Package): if not token: error(401, "Authentication needed") if not package.checkPerm(token.owner, Permission.ADD_SCREENSHOTS): error(403, "You do not have the permission to delete screenshots") if not token.canOperateOnPackage(package): error(403, "API token does not have access to the package") json = request.json if json is None or not isinstance(json, list): error(400, "Expected order body to be array") return api_order_screenshots(token, package, request.json)
def newPackage(): form = PackageForm() if form.validate_on_submit(): pkg = Package( title=form.title.data, price=form.content.data, ) db.session.add(pkg) db.session.commit() flash('Package created!', 'success') return redirect(url_for('adminPackages')) return render_template('admin/createPackage.html', title='New Package', form=form, legend='New Package')
def create_screenshot(token: APIToken, package: Package): if not token: error(401, "Authentication needed") if not package.checkPerm(token.owner, Permission.ADD_SCREENSHOTS): error(403, "You do not have the permission to create screenshots") data = request.form if "title" not in data: error(400, "Title is required in the POST data") file = request.files.get("file") if file is None: error(400, "Missing 'file' in multipart body") return api_create_screenshot(token, package, data["title"], file)
def do_create_zip_release(user: User, package: Package, title: str, file, min_v: MinetestRelease = None, max_v: MinetestRelease = None, reason: str = None, commit_hash: str = None): check_can_create_release(user, package) if commit_hash: commit_hash = commit_hash.lower() if not (len(commit_hash) == 40 and re.match(r"^[0-9a-f]+$", commit_hash)): raise LogicError( 400, "Invalid commit hash; it must be a 40 character long base16 string" ) uploaded_url, uploaded_path = upload_file(file, "zip", "a zip file") rel = PackageRelease() rel.package = package rel.title = title rel.url = uploaded_url rel.task_id = uuid() rel.commit_hash = commit_hash rel.min_rel = min_v rel.max_rel = max_v db.session.add(rel) if reason is None: msg = "Created release {}".format(rel.title) else: msg = "Created release {} ({})".format(rel.title, reason) addAuditLog(AuditSeverity.NORMAL, user, msg, package.getURL("packages.view"), package) db.session.commit() checkZipRelease.apply_async((rel.id, uploaded_path), task_id=rel.task_id) return rel
def new_package(): form = ShippingForm() form.origin.choices = [(key, key) for key in map] form.destination.choices = [(key, key) for key in map] if form.validate_on_submit(): print(form.data) data = form.data new_package = Package(sender=data["sender_name"], recipient=data["recipient_name"], origin=data["origin"], destination=data["destination"], location=data["origin"]) db.session.add(new_package) db.session.commit() return redirect('/') return render_template('shipping_request.html', form=form)
def put(self): data = api.payload if data: updatePackage = Package(destination=data['destination'], price=data['price'], days=data['days'], intenerary=data['itenerary'], inclusions=data['inclusions'], remainingSlots=data['remainingSlots'], expirationDate=data['expirationDate'], note=data['note'], hotel=data['hotel'], flight=data['flight'], isExpired=data['isExpired'] ) db.session.update(updatePackage) db.session.commit() return {'result': 'Package has been updated'}, 200 return {'error': {'statusCode': 400, 'errorCode': 'E2000', 'message': 'Please fill up the form'}}, 400
def add_packages(self): """Add fake package data to the database.""" print("Adding packages...") event_count = Event.query.count() for count in range(1, event_count + 1): event = Event.query.get(count) for num in range(self.packages_per_event): package = Package( name=self.faker.color_name() + " Package", price=self.faker.pydecimal(left_digits=5, right_digits=2, positive=True, min_value=1.0), audience=random.choice(PEOPLE_RANGES[1:])[1], description=self.faker.text(), available_packages=self.faker.pyint(min_value=1, max_value=20, step=1), package_type=random.choice(["Cash", "In-Kind"]), event=event, ) db.session.add(package) db.session.commit()
def CreatePackage(): form = forms.RegisterPackage() availableHotel = (Hotel.query.filter(Hotel.isExpired.is_(False)).filter( Hotel.isPackaged.is_(True)).all()) hotelList = [(h.id, (h.name + ' - ' + h.roomType)) for h in availableHotel] form.hotels.choices = hotelList availableTicket = (Ticket.query.filter(Ticket.isExpired.is_(False)).filter( Ticket.isPackaged.is_(True)).all()) ticketList = [(t.id, (t.flightNo + (' (' + t.origin + ' - ' + t.arrival + ')'))) for t in availableTicket] form.tickets.choices = ticketList if form.validate_on_submit(): newPackage = Package(destination=form.destination.data, days=form.days.data, expirationDate=form.expirationDate.data, remainingSlots=form.remainingSlots.data, intenerary=form.intenerary.data, inclusions=form.inclusions.data, price=form.price.data, hotel=form.hotels.data, flight=form.tickets.data) db.session.add(newPackage) user = current_user fullName = user.firstName + ' ' + user.lastName if user.role == "AD": role = "Admin" elif user.role == "RO": role = "Reservation Officer" else: role = "Financial Officer" event = (fullName + ' (' + role + ') created ' + form.destination.data) newLogTrail = LogTrail(event=event) db.session.add(newLogTrail) db.session.commit() return redirect(url_for('main.UserHomeRO')) return render_template('employee/packages/addPackage.html', form=form)
def packages(id): """Render a page that allows the user to select the sponsorship packages that will go along with theri event. """ form = EventPackagesForm() event = Event.query.get_or_404(id) packages = event.packages.all() if not current_user.is_organizer( event) and not current_user.is_administrator(): return redirect(url_for("main.index")) if form.validate_on_submit(): form_data = form.data form_data["event"] = event form_data["audience"] = EventPackagesForm.convert_choice_to_value( form.audience.data, "PEOPLE_RANGES") form_data["package_type"] = EventPackagesForm.convert_choice_to_value( form.package_type.data, "PACKAGE_TYPES") package = Package.create(**form_data) db.session.commit() return redirect(url_for("events.packages", id=id)) return render_template("events/packages.html", form=form, event=event, packages=packages)
def do_edit_package(user: User, package: Package, was_new: bool, data: dict, reason: str = None): if not package.checkPerm(user, Permission.EDIT_PACKAGE): raise LogicError(403, "You do not have permission to edit this package") if "name" in data and package.name != data["name"] and \ not package.checkPerm(user, Permission.CHANGE_NAME): raise LogicError( 403, "You do not have permission to change the package name") for alias, to in ALIASES.items(): if alias in data: data[to] = data[alias] validate(data) if "type" in data: data["type"] = PackageType.coerce(data["type"]) if "license" in data: data["license"] = get_license(data["license"]) if "media_license" in data: data["media_license"] = get_license(data["media_license"]) for key in [ "name", "title", "short_desc", "desc", "type", "license", "media_license", "repo", "website", "issueTracker", "forums" ]: if key in data: setattr(package, key, data[key]) if package.type == PackageType.TXP: package.license = package.media_license if was_new and package.type == PackageType.MOD: m = MetaPackage.GetOrCreate(package.name, {}) package.provides.append(m) if "tags" in data: package.tags.clear() for tag_id in data["tags"]: if is_int(tag_id): package.tags.append(Tag.query.get(tag_id)) else: tag = Tag.query.filter_by(name=tag_id).first() if tag is None: raise LogicError(400, "Unknown tag: " + tag_id) package.tags.append(tag) if "content_warnings" in data: package.content_warnings.clear() for warning_id in data["content_warnings"]: if is_int(warning_id): package.content_warnings.append( ContentWarning.query.get(warning_id)) else: warning = ContentWarning.query.filter_by( name=warning_id).first() if warning is None: raise LogicError(400, "Unknown warning: " + warning_id) package.content_warnings.append(warning) if not was_new: if reason is None: msg = "Edited {}".format(package.title) else: msg = "Edited {} ({})".format(package.title, reason) severity = AuditSeverity.NORMAL if user in package.maintainers else AuditSeverity.EDITOR addAuditLog(severity, user, msg, package.getDetailsURL(), package) db.session.commit() return package
def make_package(name: str, versions: List[Tuple[Optional[str], Optional[str]]]) -> List[int]: license = License.query.filter_by(name="MIT").first() author = User.query.first() mod = Package() mod.state = PackageState.APPROVED mod.name = name.lower() mod.title = name mod.license = license mod.media_license = license mod.type = PackageType.MOD mod.author = author mod.short_desc = "The content library should not be used yet as it is still in alpha" mod.desc = "This is the long desc" db.session.add(mod) rels = [] for (minv, maxv) in versions: rel = PackageRelease() rel.package = mod rel.title = "test" rel.url = "https://github.com/ezhh/handholds/archive/master.zip" if minv: rel.min_rel = MinetestRelease.query.filter_by(name=minv).first() assert rel.min_rel if maxv: rel.max_rel = MinetestRelease.query.filter_by(name=maxv).first() assert rel.max_rel rel.approved = True db.session.add(rel) rels.append(rel) db.session.flush() return [rel.id for rel in rels]
def scan_repo(): '''Scan rpm package in repository.''' Package.scan_repo()
def root_endpoint(): packages = Package.query.all() Package.advance_all_locations() return render_template('package_status.html', packages=packages)