file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/ui/molecules/sandbox-banner.svelte | Svelte | <script lang="ts">
import { fly } from "svelte/transition";
import CloseButton from "./close-button.svelte";
import { Logger } from "../../helpers/logger";
export let style = "";
export let isInElement = false;
let showBanner = true;
function closeBanner() {
Logger.debugLog("closeBanner");
showBanner = false;
}
</script>
{#if showBanner}
<div
class="rcb-ui-sandbox-banner"
{style}
out:fly={{ y: -100, duration: 300 }}
class:isInElement
>
<span class="rcb-sandbox-banner-text">Sandbox</span>
<div class="rcb-sandbox-banner-close-button-wrapper">
<CloseButton on:click={closeBanner} />
</div>
</div>
{/if}
<style>
.rcb-ui-sandbox-banner {
position: fixed;
top: 0;
z-index: 1000002;
left: 0;
width: 100%;
background-color: var(--rc-color-warning);
color: rgba(0, 0, 0, 1);
font: var(--rc-text-caption-mobile);
font-weight: bold;
text-transform: uppercase;
padding: var(--rc-spacing-gapSmall-mobile);
display: flex;
justify-content: center;
align-items: center;
}
.rcb-ui-sandbox-banner.isInElement {
position: absolute;
}
.rcb-sandbox-banner-close-button-wrapper {
position: absolute;
right: var(--rc-spacing-gapMedium-mobile);
top: 50%;
transform: translateY(-50%);
color: black;
}
:global(.rcb-sandbox-banner-close-button-icon) {
color: black;
height: var(--rc-text-caption-mobile-font-size);
}
@container layout-query-container (width >= 768px) {
:global(.rcb-sandbox-banner-close-button-icon) {
height: var(--rc-text-caption-desktop-font-size);
}
.rcb-ui-sandbox-banner {
padding: var(--rc-spacing-gapMedium-desktop);
font: var(--rc-text-caption-desktop);
font-weight: bold;
}
.rcb-sandbox-banner-close-button-wrapper {
right: var(--rc-spacing-gapMedium-desktop);
}
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/molecules/secure-checkout-rc.svelte | Svelte | <script lang="ts">
import Localized from "../localization/localized.svelte";
import { LocalizationKeys } from "../localization/supportedLanguages";
import { getContext } from "svelte";
import { translatorContextKey } from "../localization/constants";
import { Translator } from "../localization/translator";
import { formatPrice } from "../../helpers/price-labels";
import { getNextRenewalDate } from "../../helpers/duration-helper";
import type { BrandingInfoResponse } from "../../networking/responses/branding-response";
import type { SubscriptionOption } from "../../entities/offerings";
import { type Writable } from "svelte/store";
export let brandingInfo: BrandingInfoResponse | null = null;
export let subscriptionOption: SubscriptionOption | null = null;
const translator = getContext<Writable<Translator>>(translatorContextKey);
$: termsInfo = brandingInfo
? $translator.translate(LocalizationKeys.PaymentEntryPageTermsInfo, {
appName: brandingInfo?.app_name,
})
: null;
$: trialInfo =
subscriptionOption?.base?.price &&
subscriptionOption?.trial?.period &&
subscriptionOption?.base?.period &&
subscriptionOption?.base?.period?.unit
? $translator.translate(LocalizationKeys.PaymentEntryPageTrialInfo, {
price: formatPrice(
subscriptionOption?.base?.price.amountMicros,
subscriptionOption?.base?.price.currency,
$translator.locale || $translator.fallbackLocale,
),
perFrequency: $translator.translatePeriodFrequency(
subscriptionOption?.base?.period?.number || 1,
subscriptionOption?.base?.period?.unit,
{ useMultipleWords: true },
),
renewalDate: $translator.translateDate(
getNextRenewalDate(
new Date(),
subscriptionOption.trial.period || subscriptionOption.base.period,
true,
) as Date,
{ year: "numeric", month: "long", day: "numeric" },
),
})
: null;
</script>
<div class="footer-caption-container">
{#if termsInfo}
<p class="footer-caption">
{termsInfo}
</p>
{/if}
{#if trialInfo}
<p class="footer-caption">
{trialInfo}
</p>
{/if}
<p class="footer-caption">
<Localized key={LocalizationKeys.PaymentEntryPagePaymentStepTitle} />
</p>
</div>
<style>
.footer-caption-container {
display: flex;
flex-direction: column;
gap: var(--rc-spacing-gapXLarge-mobile);
}
.footer-caption {
font: var(--rc-text-caption-mobile);
color: var(--rc-color-grey-text-light);
text-align: center;
margin: 0;
}
@container layout-query-container (width >= 768px) {
.footer-caption {
font: var(--rc-text-caption-desktop);
}
.footer-caption-container {
gap: var(--rc-spacing-gapLarge-desktop);
}
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/molecules/stripe-payment-elements.svelte | Svelte | <script lang="ts">
import { getContext, onMount } from "svelte";
import type {
Appearance,
ConfirmationToken,
Stripe,
StripeElementLocale,
StripeElements,
StripeError,
StripePaymentElement,
StripePaymentElementChangeEvent,
} from "@stripe/stripe-js";
import { type BrandingInfoResponse } from "../../networking/responses/branding-response";
import { Theme } from "../theme/theme";
import { translatorContextKey } from "../localization/constants";
import { Translator } from "../localization/translator";
import { type GatewayParams } from "../../networking/responses/stripe-elements";
import { DEFAULT_FONT_FAMILY } from "../theme/text";
import { StripeService } from "../../stripe/stripe-service";
import { type Writable } from "svelte/store";
import {
type PaymentElementError,
PaymentElementErrorCode,
} from "../types/payment-element-error";
import { type TaxCustomerDetails } from "../ui-types";
export let gatewayParams: GatewayParams;
export let brandingInfo: BrandingInfoResponse | null;
export let taxCollectionEnabled: boolean;
export let onLoadingComplete: () => void;
export let onError: (error: PaymentElementError) => void;
export let onPaymentInfoChange: (params: {
complete: boolean;
paymentMethod: string | undefined;
}) => void;
export let onSubmissionSuccess: () => void;
export let onConfirmationSuccess: () => void;
export let onTaxCustomerDetailsUpdated: (
customerDetails: TaxCustomerDetails,
) => void;
export let stripeLocale: StripeElementLocale | undefined = undefined;
export async function submit() {
if (!elements) return;
const { error: submitError } = await elements.submit();
if (submitError) {
handleFormSubmissionError(submitError);
} else {
onSubmissionSuccess();
}
}
export async function confirm(clientSecret: string) {
if (!stripe || !elements) return;
const confirmError = await StripeService.confirmIntent(
stripe,
elements,
clientSecret,
);
if (confirmError) {
handleFormSubmissionError(confirmError);
} else {
onConfirmationSuccess();
}
}
$: if (elements) {
(async () => {
const elementsConfiguration = gatewayParams.elements_configuration;
if (!elementsConfiguration) return;
await StripeService.updateElementsConfiguration(
elements,
elementsConfiguration,
);
})();
}
function handleFormSubmissionError(error: StripeError) {
if (StripeService.isStripeHandledCardError(error)) {
onError({
code: PaymentElementErrorCode.HandledFormSubmissionError,
gatewayErrorCode: error.code,
message: error.message,
});
} else {
onError({
code: PaymentElementErrorCode.UnhandledFormSubmissionError,
gatewayErrorCode: error.code,
message: error.message,
});
}
}
let stripe: Stripe | null = null;
let unsafeElements: StripeElements | null = null;
let elements: StripeElements | null = null;
let lastTaxCustomerDetails: TaxCustomerDetails | undefined = undefined;
let spacing = new Theme().spacing;
let stripeVariables: undefined | Appearance["variables"];
let viewport: "mobile" | "desktop" = "mobile";
// Maybe extract this to a hook
function updateStripeVariables() {
const isMobile =
window.matchMedia && window.matchMedia("(max-width: 767px)").matches;
if (isMobile) {
viewport = "mobile";
} else {
viewport = "desktop";
}
stripeVariables = {
fontSizeBase: "14px",
fontFamily: DEFAULT_FONT_FAMILY,
spacingGridRow: spacing.gapXLarge[viewport],
};
}
let resizeTimeout: number | undefined;
function onResize() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
updateStripeVariables();
}, 150);
}
const translator = getContext<Writable<Translator>>(translatorContextKey);
$: initialLocale = ($translator.locale ||
$translator.fallbackLocale) as string;
$: stripeLocale = getLocaleToUse(initialLocale);
$: {
// @ts-ignore
if (unsafeElements && unsafeElements._elements.length > 0) {
elements = unsafeElements;
}
}
/**
* This function converts some particular locales to the ones that stripe supports.
* Finally falls back to 'auto' if the initialLocale is not supported by stripe.
* @param initialLocale
*/
const getLocaleToUse = (initialLocale: string): StripeElementLocale => {
// These locale that we support are not supported by stripe.
// if any of these is passed we fallback to 'auto' so that
// stripe will pick up the locale from the browser.
const stripeUnsupportedLocale = ["ca", "hi", "uk"];
if (stripeUnsupportedLocale.includes(initialLocale)) {
return "auto";
}
const mappedLocale: Record<string, StripeElementLocale> = {
zh_Hans: "zh",
zh_Hant: "zh",
};
if (Object.keys(mappedLocale).includes(initialLocale)) {
return mappedLocale[initialLocale];
}
return initialLocale as StripeElementLocale;
};
async function triggerTaxDetailsUpdated() {
if (!elements || !stripe) return;
const { error: submitError } = await elements.submit();
if (submitError) {
handleFormSubmissionError(submitError);
return;
}
const { error: confirmationError, confirmationToken } =
await stripe.createConfirmationToken({
elements: elements,
});
if (confirmationError) {
handleFormSubmissionError(confirmationError);
return;
}
const { countryCode, postalCode } =
getCountryAndPostalCodeFromConfirmationToken(confirmationToken);
if (
countryCode === lastTaxCustomerDetails?.countryCode &&
postalCode === lastTaxCustomerDetails?.postalCode
) {
return;
}
lastTaxCustomerDetails = { countryCode, postalCode };
onTaxCustomerDetailsUpdated({
countryCode,
postalCode,
});
}
function getCountryAndPostalCodeFromConfirmationToken(
confirmationToken: ConfirmationToken,
): { countryCode?: string; postalCode?: string } {
const billingAddress =
confirmationToken.payment_method_preview?.billing_details?.address;
const countryCode = billingAddress?.country ?? undefined;
const postalCode = billingAddress?.postal_code ?? undefined;
return { countryCode, postalCode };
}
onMount(() => {
updateStripeVariables();
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
};
});
onMount(() => {
let paymentElement: StripePaymentElement | null = null;
let isMounted = true;
(async () => {
try {
const { stripe: stripeInstance, elements: elementsInstance } =
await StripeService.initializeStripe(
gatewayParams,
brandingInfo,
stripeLocale,
stripeVariables,
viewport,
);
if (!isMounted) return;
stripe = stripeInstance;
unsafeElements = elementsInstance;
paymentElement = StripeService.createPaymentElement(
unsafeElements,
brandingInfo?.app_name,
);
paymentElement.mount("#payment-element");
paymentElement.on("ready", () => {
onLoadingComplete();
});
paymentElement.on(
"change",
async (event: StripePaymentElementChangeEvent) => {
if (
taxCollectionEnabled &&
event.complete &&
event.value.type === "card"
) {
await triggerTaxDetailsUpdated();
}
onPaymentInfoChange({
complete: event.complete,
paymentMethod: event.complete ? event.value.type : undefined,
});
},
);
paymentElement.on("loaderror", (event) => {
isMounted = false;
onError({
code: PaymentElementErrorCode.ErrorLoadingStripe,
gatewayErrorCode: event.error.code,
message: event.error.message,
});
onLoadingComplete();
});
} catch (error) {
if (!isMounted) return;
onError({
code: PaymentElementErrorCode.ErrorLoadingStripe,
gatewayErrorCode: undefined,
message: error instanceof Error ? error.message : String(error),
});
onLoadingComplete();
}
})();
return () => {
if (isMounted) {
isMounted = false;
paymentElement?.destroy();
}
};
});
</script>
<div id="payment-element"></div>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/organisms/product-info.svelte | Svelte | <script lang="ts">
import {
type Product,
type PurchaseOption,
ProductType,
type SubscriptionOption,
} from "../../entities/offerings";
import PricingTable from "../molecules/pricing-table.svelte";
import ProductInfoHeader from "../molecules/product-header.svelte";
import PricingSummary from "../molecules/pricing-summary.svelte";
import { type PriceBreakdown } from "../ui-types";
export let productDetails: Product;
export let purchaseOption: PurchaseOption;
export let showProductDescription: boolean;
export let priceBreakdown: PriceBreakdown;
const isSubscription =
productDetails.productType === ProductType.Subscription;
const subscriptionOption = purchaseOption as SubscriptionOption;
const basePhase = subscriptionOption?.base;
const trialPhase = subscriptionOption?.trial;
</script>
<section>
<div class="rcb-pricing-info" class:has-expanded-details={isSubscription}>
<ProductInfoHeader {productDetails} {showProductDescription} />
<PricingSummary {priceBreakdown} {basePhase} {trialPhase} />
<PricingTable {priceBreakdown} {trialPhase} />
</div>
</section>
<style>
.rcb-pricing-info {
display: flex;
flex-direction: column;
font: var(--rc-text-body1-mobile);
gap: var(--rc-spacing-gapLarge-mobile);
user-select: none;
}
.rcb-pricing-info {
gap: var(--rc-spacing-gapXXLarge-mobile);
}
@container layout-query-container (width < 768px) {
.rcb-pricing-info {
margin-top: var(--rc-spacing-gapXLarge-mobile);
}
}
@container layout-query-container (width >= 768px) {
.rcb-pricing-info {
margin-top: calc(var(--rc-spacing-gapXXLarge-desktop) * 2);
gap: var(--rc-spacing-gapXXXLarge-desktop);
}
.rcb-pricing-info.has-expanded-details {
gap: var(--rc-spacing-gapXXXLarge-desktop);
}
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/pages/email-entry-page.svelte | Svelte | <script lang="ts">
import Button from "../atoms/button.svelte";
import ModalFooter from "../layout/modal-footer.svelte";
import ModalSection from "../layout/modal-section.svelte";
import RowLayout from "../layout/row-layout.svelte";
import { validateEmail } from "../../helpers/validators";
import { PurchaseFlowError } from "../../helpers/purchase-operation-helper";
import { getContext, onMount } from "svelte";
import Localized from "../localization/localized.svelte";
import { translatorContextKey } from "../localization/constants";
import { Translator } from "../localization/translator";
import { LocalizationKeys } from "../localization/supportedLanguages";
import SecureCheckoutRc from "../molecules/secure-checkout-rc.svelte";
import { type ContinueHandlerParams } from "../ui-types";
import { eventsTrackerContextKey } from "../constants";
import { type IEventsTracker } from "../../behavioural-events/events-tracker";
import { createCheckoutBillingFormErrorEvent } from "../../behavioural-events/sdk-event-helpers";
import { SDKEventName } from "../../behavioural-events/sdk-events";
import { type Writable } from "svelte/store";
export let onContinue: (params: ContinueHandlerParams) => void;
export let processing: boolean;
export let lastError: PurchaseFlowError | null;
const eventsTracker = getContext(eventsTrackerContextKey) as IEventsTracker;
$: email = "";
$: errorMessage = lastError?.message || "";
$: inputClass = (lastError?.message ?? errorMessage) !== "" ? "error" : "";
const handleContinue = async () => {
errorMessage = validateEmail(email) ?? "";
if (errorMessage !== "") {
const event = createCheckoutBillingFormErrorEvent({
errorCode: null,
errorMessage,
});
eventsTracker.trackSDKEvent(event);
} else {
eventsTracker.trackSDKEvent({
eventName: SDKEventName.CheckoutBillingFormSubmit,
});
onContinue({ authInfo: { email } });
}
};
onMount(() => {
eventsTracker.trackSDKEvent({
eventName: SDKEventName.CheckoutBillingFormImpression,
});
});
const translator: Writable<Translator> = getContext(translatorContextKey);
</script>
<div class="rcb-state-container">
<span class="rcb-auth-info-title">
<label for="email">
<Localized key={LocalizationKeys.EmailEntryPageEmailStepTitle} />
</label></span
>
<form on:submit|preventDefault={handleContinue}>
<ModalSection>
<div class="rcb-form-container">
<div class="rcb-form-input {inputClass}">
<input
id="email"
name="email"
inputmode="email"
placeholder={$translator.translate(
LocalizationKeys.EmailEntryPageEmailInputPlaceholder,
)}
autocapitalize="off"
autocomplete="email"
data-testid="email"
bind:value={email}
/>
</div>
{#if errorMessage !== ""}
<div class="rcb-form-error">{errorMessage}</div>
{/if}
</div>
</ModalSection>
<ModalFooter>
<RowLayout>
<Button disabled={processing} type="submit" loading={processing}>
<Localized key={LocalizationKeys.EmailEntryPageButtonContinue} />
</Button>
</RowLayout>
<div class="secure-checkout-container">
<SecureCheckoutRc />
</div>
</ModalFooter>
</form>
</div>
<style>
.rcb-auth-info-title {
font: var(--rc-text-titleLarge-mobile);
}
.secure-checkout-container {
margin-top: var(--rc-spacing-gapXXLarge-mobile);
}
@container layout-query-container (width >= 768px) {
.rcb-auth-info-title {
font: var(--rc-text-titleLarge-desktop);
}
.secure-checkout-container {
margin-top: var(--rc-spacing-gapXXLarge-desktop);
}
}
.rcb-state-container {
display: flex;
flex-direction: column;
flex-grow: 1;
user-select: none;
}
form {
display: flex;
flex-direction: column;
flex-grow: 1;
}
.rcb-form-container {
display: flex;
flex-direction: column;
width: 100%;
margin-top: var(--rc-spacing-gapXLarge-desktop);
margin-bottom: var(--rc-spacing-gapXLarge-desktop);
}
@media screen and (max-width: 767px) {
.rcb-form-container {
margin-top: var(--rc-spacing-gapXLarge-mobile);
margin-bottom: var(--rc-spacing-gapXLarge-mobile);
}
}
.rcb-form-label {
margin-top: var(--rc-spacing-gapSmall-desktop);
margin-bottom: var(--rc-spacing-gapSmall-desktop);
font: var(--rc-text-body1-mobile);
display: block;
}
@container layout-query-container (width >= 768px) {
.rcb-form-label {
font: var(--rc-text-body1-desktop);
}
}
.rcb-form-input.error input {
border-color: var(--rc-color-error);
}
.rcb-form-error {
margin-top: var(--rc-spacing-gapSmall-desktop);
font: var(--rc-text-body1-mobile);
color: var(--rc-color-error);
}
@container layout-query-container (width >= 768px) {
.rcb-form-error {
font: var(--rc-text-body1-desktop);
}
}
input {
width: 100%;
box-sizing: border-box;
border: 1px solid var(--rc-color-grey-ui-dark);
border-radius: var(--rc-shape-input-border-radius);
font: var(--rc-text-body1-mobile);
height: var(--rc-spacing-inputHeight-desktop);
background: var(--rc-color-input-background);
color: inherit;
}
@container layout-query-container (width < 768px) {
input {
padding-left: var(--rc-spacing-gapLarge-mobile);
height: var(--rc-spacing-inputHeight-mobile);
}
}
@container layout-query-container (width >= 768px) {
input {
font: var(--rc-text-body1-desktop);
padding-left: var(--rc-spacing-gapLarge-desktop);
}
.rcb-state-container {
max-width: 50vw;
flex-grow: 0;
}
}
input:focus {
outline: none;
border: 1px solid var(--rc-color-focus);
}
input::placeholder {
color: var(--rc-color-grey-ui-dark);
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/pages/error-page.svelte | Svelte | <script lang="ts">
import {
PurchaseFlowError,
PurchaseFlowErrorCode,
} from "../../helpers/purchase-operation-helper";
import IconError from "../atoms/icons/icon-error.svelte";
import { getContext, onMount } from "svelte";
import { Logger } from "../../helpers/logger.js";
import MessageLayout from "../layout/message-layout.svelte";
import { type Product, ProductType } from "../../entities/offerings";
import { Translator } from "../localization/translator";
import { translatorContextKey } from "../localization/constants";
import Localized from "../localization/localized.svelte";
import { LocalizationKeys } from "../localization/supportedLanguages";
import { type Writable } from "svelte/store";
interface Props {
lastError: PurchaseFlowError | null;
supportEmail: string | null;
productDetails: Product;
onContinue: () => void;
}
const { lastError, supportEmail, productDetails, onContinue }: Props =
$props();
const error: PurchaseFlowError = $derived(
lastError ??
new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
"Unknown error without state set.",
),
);
const translator: Writable<Translator> = getContext(translatorContextKey);
onMount(() => {
Logger.errorLog(
`Displayed error: ${PurchaseFlowErrorCode[error.errorCode]}. Message: ${error.message ?? "None"}. Underlying error: ${error.underlyingErrorMessage ?? "None"}`,
);
});
function getTranslatedErrorTitle(): string {
switch (error.errorCode) {
case PurchaseFlowErrorCode.AlreadyPurchasedError:
if (productDetails.productType === ProductType.Subscription) {
return $translator.translate(
LocalizationKeys.ErrorPageErrorTitleAlreadySubscribed,
);
} else {
return $translator.translate(
LocalizationKeys.ErrorPageErrorTitleAlreadyPurchased,
);
}
default:
return $translator.translate(
LocalizationKeys.ErrorPageErrorTitleOtherErrors,
);
}
}
function getTranslatedErrorMessage(): string | undefined {
const publicErrorCode = error.getErrorCode();
switch (error.errorCode) {
case PurchaseFlowErrorCode.UnknownError:
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageUnknownError,
{ errorCode: publicErrorCode },
);
case PurchaseFlowErrorCode.ErrorSettingUpPurchase:
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageErrorSettingUpPurchase,
{ errorCode: publicErrorCode },
);
case PurchaseFlowErrorCode.ErrorChargingPayment:
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageErrorChargingPayment,
{ errorCode: publicErrorCode },
);
case PurchaseFlowErrorCode.NetworkError:
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageNetworkError,
{ errorCode: publicErrorCode },
);
case PurchaseFlowErrorCode.MissingEmailError:
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageMissingEmailError,
{ errorCode: publicErrorCode },
);
case PurchaseFlowErrorCode.AlreadyPurchasedError:
if (productDetails.productType === ProductType.Subscription) {
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageAlreadySubscribed,
{ errorCode: publicErrorCode },
);
} else {
return $translator.translate(
LocalizationKeys.ErrorPageErrorMessageAlreadyPurchased,
{ errorCode: publicErrorCode },
);
}
}
}
</script>
<MessageLayout
title={getTranslatedErrorTitle()}
{onContinue}
type="error"
closeButtonTitle={$translator.translate(LocalizationKeys.ErrorButtonTryAgain)}
>
{#snippet icon()}
<IconError />
{/snippet}
{#snippet message()}
{getTranslatedErrorMessage()}
{#if supportEmail}
<br />
<Localized key={LocalizationKeys.ErrorPageIfErrorPersists} />
<a href="mailto:{supportEmail}">{supportEmail}</a>.
{/if}
{/snippet}
</MessageLayout>
<style>
a {
color: var(--rc-color-primary);
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/pages/payment-entry-loading-page.svelte | Svelte | <script>
import Loading from "../molecules/loading.svelte";
</script>
<Loading />
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/pages/payment-entry-page.svelte | Svelte | <script lang="ts">
import { getContext, onMount } from "svelte";
import type { StripeElementLocale } from "@stripe/stripe-js";
import type { Product, PurchaseOption } from "../../entities/offerings";
import { type BrandingInfoResponse } from "../../networking/responses/branding-response";
import IconError from "../atoms/icons/icon-error.svelte";
import MessageLayout from "../layout/message-layout.svelte";
import { translatorContextKey } from "../localization/constants";
import { Translator } from "../localization/translator";
import { LocalizationKeys } from "../localization/supportedLanguages";
import SecureCheckoutRc from "../molecules/secure-checkout-rc.svelte";
import {
PurchaseFlowError,
PurchaseFlowErrorCode,
PurchaseOperationHelper,
} from "../../helpers/purchase-operation-helper";
import {
type TaxCustomerDetails,
type ContinueHandlerParams,
type PriceBreakdown,
} from "../ui-types";
import { type IEventsTracker } from "../../behavioural-events/events-tracker";
import { eventsTrackerContextKey } from "../constants";
import {
createCheckoutPaymentFormSubmitEvent,
createCheckoutPaymentGatewayErrorEvent,
} from "../../behavioural-events/sdk-event-helpers";
import { SDKEventName } from "../../behavioural-events/sdk-events";
import Loading from "../molecules/loading.svelte";
import { type Writable } from "svelte/store";
import {
type PaymentElementError,
PaymentElementErrorCode,
} from "../types/payment-element-error";
import PaymentButton from "../molecules/payment-button.svelte";
import StripePaymentElements from "../molecules/stripe-payment-elements.svelte";
import { type GatewayParams } from "../../networking/responses/stripe-elements";
export let onContinue: (params?: ContinueHandlerParams) => void;
export let gatewayParams: GatewayParams = {};
export let priceBreakdown: PriceBreakdown;
export let processing = false;
export let productDetails: Product;
export let purchaseOption: PurchaseOption;
export let brandingInfo: BrandingInfoResponse | null;
export let purchaseOperationHelper: PurchaseOperationHelper;
export let onTaxCustomerDetailsUpdated: (
customerDetails: TaxCustomerDetails,
) => void;
let isStripeLoading = true;
let stripeLocale: StripeElementLocale | undefined;
let stripeSubmit: () => Promise<void>;
let stripeConfirm: (clientSecret: string) => Promise<void>;
let isPaymentInfoComplete = false;
let selectedPaymentMethod: string | undefined = undefined;
let modalErrorMessage: string | undefined = undefined;
let clientSecret: string | undefined = undefined;
const subscriptionOption =
productDetails.subscriptionOptions?.[purchaseOption.id];
const eventsTracker = getContext(eventsTrackerContextKey) as IEventsTracker;
const translator = getContext<Writable<Translator>>(translatorContextKey);
onMount(() => {
eventsTracker.trackSDKEvent({
eventName: SDKEventName.CheckoutPaymentFormImpression,
});
});
function handleStripeLoadingComplete() {
isStripeLoading = false;
}
function handlePaymentInfoChange({
complete,
paymentMethod,
}: {
complete: boolean;
paymentMethod: string | undefined;
}) {
selectedPaymentMethod = paymentMethod;
isPaymentInfoComplete = complete;
}
async function handleSubmit(): Promise<void> {
if (processing) return;
const event = createCheckoutPaymentFormSubmitEvent({
selectedPaymentMethod: selectedPaymentMethod ?? null,
});
eventsTracker.trackSDKEvent(event);
processing = true;
await stripeSubmit();
}
async function handlePaymentSubmissionSuccess(): Promise<void> {
// Get client secret if not already present
if (!clientSecret) {
try {
const response = await purchaseOperationHelper.checkoutComplete();
clientSecret = response?.gateway_params?.client_secret;
if (!clientSecret) {
throw new Error("Failed to complete checkout");
}
} catch (error) {
handleStripeElementError(error as PaymentElementError);
return;
}
}
await stripeConfirm(clientSecret);
}
function handleStripeElementError(error: PaymentElementError) {
processing = false;
const event = createCheckoutPaymentGatewayErrorEvent({
errorCode: error.gatewayErrorCode ?? "",
errorMessage: error.message ?? "",
});
eventsTracker.trackSDKEvent(event);
if (error.code === PaymentElementErrorCode.HandledFormSubmissionError) {
return;
}
if (error.code === PaymentElementErrorCode.UnhandledFormSubmissionError) {
modalErrorMessage = error.message;
} else {
onContinue({
error: new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"Failed to initialize payment form",
error.message,
),
});
}
}
const handleErrorTryAgain = () => {
modalErrorMessage = undefined;
};
</script>
<div class="rc-checkout-container">
{#if isStripeLoading || processing}
<Loading />
{/if}
<!-- <TextSeparator text="Pay by card" /> -->
<form
on:submit|preventDefault={handleSubmit}
data-testid="payment-form"
class="rc-checkout-form"
class:hidden={isStripeLoading || processing}
>
<div class="rc-checkout-form-container" hidden={!!modalErrorMessage}>
<div class="rc-payment-element-container">
<StripePaymentElements
bind:submit={stripeSubmit}
bind:confirm={stripeConfirm}
bind:stripeLocale
{gatewayParams}
{brandingInfo}
onLoadingComplete={handleStripeLoadingComplete}
onError={handleStripeElementError}
onPaymentInfoChange={handlePaymentInfoChange}
onSubmissionSuccess={handlePaymentSubmissionSuccess}
onConfirmationSuccess={onContinue}
taxCollectionEnabled={priceBreakdown.taxCollectionEnabled}
{onTaxCustomerDetailsUpdated}
/>
</div>
<div class="rc-checkout-pay-container">
{#if !modalErrorMessage}
<PaymentButton
disabled={processing ||
!isPaymentInfoComplete ||
priceBreakdown.taxCalculationStatus === "loading"}
{subscriptionOption}
/>
{/if}
<div class="rc-checkout-secure-container">
<SecureCheckoutRc {brandingInfo} {subscriptionOption} />
</div>
</div>
</div>
{#if modalErrorMessage}
<MessageLayout
title={null}
type="error"
closeButtonTitle={$translator.translate(
LocalizationKeys.ErrorButtonTryAgain,
)}
onContinue={handleErrorTryAgain}
>
{#snippet icon()}
<IconError />
{/snippet}
{#snippet message()}
{modalErrorMessage}
{/snippet}
</MessageLayout>
{/if}
</form>
</div>
<style>
.rc-checkout-secure-container {
margin-top: var(--rc-spacing-gapXLarge-mobile);
}
.rc-checkout-container {
display: flex;
flex-direction: column;
gap: var(--rc-spacing-gapXLarge-mobile);
user-select: none;
}
.rc-checkout-pay-container {
display: flex;
flex-direction: column;
margin-top: var(--rc-spacing-gapXLarge-mobile);
}
.rc-checkout-form-container {
width: 100%;
}
.rc-payment-element-container {
/* The standard height of the payment form from Stripe */
/* Added to avoid the card getting smaller while loading */
min-height: 210px;
}
.hidden {
visibility: hidden;
}
@container layout-query-container (width <= 767px) {
.rc-checkout-pay-container {
flex-grow: 1;
justify-content: flex-end;
}
.rc-checkout-form {
flex-grow: 1;
}
.rc-checkout-form-container {
height: 100%;
display: flex;
flex-direction: column;
}
.rc-checkout-container {
flex-grow: 1;
}
}
@container layout-query-container (width >= 768px) {
.rc-checkout-secure-container {
margin-top: var(--rc-spacing-gapXLarge-desktop);
}
.rc-checkout-container {
gap: var(--rc-spacing-gapXLarge-desktop);
}
.rc-checkout-pay-container {
margin-top: var(--rc-spacing-gapXLarge-desktop);
}
}
</style>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/pages/success-page.svelte | Svelte | <script lang="ts">
import IconSuccess from "../atoms/icons/icon-success.svelte";
import MessageLayout from "../layout/message-layout.svelte";
import { type Product, ProductType } from "../../entities/offerings";
import { getContext, onMount } from "svelte";
import { translatorContextKey } from "../localization/constants";
import { Translator } from "../localization/translator";
import Localized from "../localization/localized.svelte";
import { LocalizationKeys } from "../localization/supportedLanguages";
import { SDKEventName } from "../../behavioural-events/sdk-events";
import { type IEventsTracker } from "../../behavioural-events/events-tracker";
import { eventsTrackerContextKey } from "../constants";
import { type ContinueHandlerParams } from "../ui-types";
import { type Writable } from "svelte/store";
export let productDetails: Product;
export let onContinue: (params?: ContinueHandlerParams) => void;
const isSubscription =
productDetails.productType === ProductType.Subscription;
const translator: Writable<Translator> = getContext(translatorContextKey);
const eventsTracker = getContext(eventsTrackerContextKey) as IEventsTracker;
function handleContinue() {
eventsTracker.trackSDKEvent({
eventName: SDKEventName.CheckoutPurchaseSuccessfulDismiss,
properties: {
ui_element: "go_back_to_app",
},
});
onContinue();
}
onMount(() => {
eventsTracker.trackSDKEvent({
eventName: SDKEventName.CheckoutPurchaseSuccessfulImpression,
});
});
</script>
<MessageLayout
type="success"
title={$translator.translate(LocalizationKeys.SuccessPagePurchaseSuccessful)}
onContinue={handleContinue}
closeButtonTitle={$translator.translate(
LocalizationKeys.SuccessPageButtonClose,
)}
>
{#snippet icon()}
<IconSuccess />
{/snippet}
{#snippet message()}
{#if isSubscription}
<Localized key={LocalizationKeys.SuccessPageSubscriptionNowActive} />
{/if}
{/snippet}
</MessageLayout>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/purchases-ui-inner.svelte | Svelte | <script lang="ts">
import PaymentEntryPage from "./pages/payment-entry-page.svelte";
import EmailEntryPage from "./pages/email-entry-page.svelte";
import ErrorPage from "./pages/error-page.svelte";
import SuccessPage from "./pages/success-page.svelte";
import LoadingPage from "./pages/payment-entry-loading-page.svelte";
import {
type PriceBreakdown,
type ContinueHandlerParams,
type CurrentPage,
type TaxCustomerDetails,
} from "./ui-types";
import { type BrandingInfoResponse } from "../networking/responses/branding-response";
import type { Product, PurchaseOption } from "../main";
import ProductInfo from "./organisms/product-info.svelte";
import {
PurchaseFlowError,
PurchaseOperationHelper,
} from "../helpers/purchase-operation-helper";
import Template from "./layout/template.svelte";
import { type GatewayParams } from "../networking/responses/stripe-elements";
export let currentPage: CurrentPage;
export let brandingInfo: BrandingInfoResponse | null;
export let productDetails: Product;
export let purchaseOptionToUse: PurchaseOption;
export let isSandbox: boolean = false;
export let handleContinue: (params?: ContinueHandlerParams) => void;
export let closeWithError: () => void;
export let onClose: (() => void) | undefined = undefined;
export let lastError: PurchaseFlowError | null;
export let priceBreakdown: PriceBreakdown;
export let purchaseOperationHelper: PurchaseOperationHelper;
export let isInElement: boolean = false;
export let gatewayParams: GatewayParams;
export let onTaxCustomerDetailsUpdated: (
customerDetails: TaxCustomerDetails,
) => void;
</script>
<Template {brandingInfo} {isInElement} {isSandbox} {onClose}>
{#snippet navbarContent()}
<ProductInfo
{productDetails}
purchaseOption={purchaseOptionToUse}
showProductDescription={brandingInfo?.appearance
?.show_product_description ?? false}
{priceBreakdown}
/>
{/snippet}
{#snippet mainContent()}
{#if currentPage === "email-entry" || currentPage === "email-entry-processing"}
<EmailEntryPage
onContinue={handleContinue}
processing={currentPage === "email-entry-processing"}
{lastError}
/>
{/if}
{#if currentPage === "payment-entry-loading"}
<LoadingPage />
{/if}
{#if currentPage === "payment-entry" || currentPage === "payment-entry-processing"}
<PaymentEntryPage
onContinue={handleContinue}
processing={currentPage === "payment-entry-processing"}
{productDetails}
purchaseOption={purchaseOptionToUse}
{brandingInfo}
{purchaseOperationHelper}
{gatewayParams}
{priceBreakdown}
{onTaxCustomerDetailsUpdated}
/>
{/if}
{#if currentPage === "error"}
<ErrorPage
{lastError}
{productDetails}
supportEmail={brandingInfo?.support_email ?? null}
onContinue={closeWithError}
/>
{/if}
{#if currentPage === "success"}
<SuccessPage {productDetails} onContinue={handleContinue} />
{/if}
{/snippet}
</Template>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/purchases-ui.svelte | Svelte | <script lang="ts">
import { onMount, setContext, onDestroy } from "svelte";
import type { Package, Product, PurchaseOption, Purchases } from "../main";
import { type BrandingInfoResponse } from "../networking/responses/branding-response";
import {
PurchaseFlowError,
PurchaseFlowErrorCode,
PurchaseOperationHelper,
} from "../helpers/purchase-operation-helper";
import { type RedemptionInfo } from "../entities/redemption-info";
import {
type CustomTranslations,
Translator,
} from "./localization/translator";
import {
englishLocale,
translatorContextKey,
} from "./localization/constants";
import {
type PriceBreakdown,
type TaxCustomerDetails,
type CurrentPage,
} from "./ui-types";
import PurchasesUiInner from "./purchases-ui-inner.svelte";
import { type ContinueHandlerParams } from "./ui-types";
import { type IEventsTracker } from "../behavioural-events/events-tracker";
import { eventsTrackerContextKey } from "./constants";
import { createCheckoutFlowErrorEvent } from "../behavioural-events/sdk-event-helpers";
import type { PurchaseMetadata } from "../entities/offerings";
import { writable } from "svelte/store";
import { GatewayParams } from "../networking/responses/stripe-elements";
import { ALLOW_TAX_CALCULATION_FF } from "../helpers/constants";
export let customerEmail: string | undefined;
export let appUserId: string;
export let rcPackage: Package;
export let purchaseOption: PurchaseOption;
export let metadata: PurchaseMetadata | undefined;
export let brandingInfo: BrandingInfoResponse | null;
export let onFinished: (
operationSessionId: string,
redemptionInfo: RedemptionInfo | null,
) => void;
export let onError: (error: PurchaseFlowError) => void;
// We don't have a close button in the UI, but we might add one soon
export let onClose: (() => void) | undefined = undefined;
export let purchases: Purchases;
export let eventsTracker: IEventsTracker;
export let purchaseOperationHelper: PurchaseOperationHelper;
export let selectedLocale: string = englishLocale;
export let defaultLocale: string = englishLocale;
export let customTranslations: CustomTranslations = {};
export let isInElement: boolean = false;
let productDetails: Product = rcPackage.webBillingProduct;
let lastError: PurchaseFlowError | null = null;
const productId = rcPackage.webBillingProduct.identifier ?? null;
let currentPage: CurrentPage | null = null;
let redemptionInfo: RedemptionInfo | null = null;
let operationSessionId: string | null = null;
let gatewayParams: GatewayParams = {};
let priceBreakdown: PriceBreakdown = {
currency: productDetails.currentPrice.currency,
totalAmountInMicros: productDetails.currentPrice.amountMicros,
totalExcludingTaxInMicros: productDetails.currentPrice.amountMicros,
taxCollectionEnabled: false,
taxCalculationStatus: null,
pendingReason: null,
taxAmountInMicros: null,
taxBreakdown: null,
};
if (
ALLOW_TAX_CALCULATION_FF &&
brandingInfo?.gateway_tax_collection_enabled
) {
priceBreakdown.taxCollectionEnabled = true;
priceBreakdown.taxCalculationStatus = "pending";
}
// Setting the context for the Localized components
let translator: Translator = new Translator(
customTranslations,
selectedLocale,
defaultLocale,
);
var translatorStore = writable(translator);
setContext(translatorContextKey, translatorStore);
onMount(() => {
if (!isInElement) {
document.documentElement.style.height = "100%";
document.body.style.height = "100%";
document.documentElement.style.overflow = "hidden";
}
});
onDestroy(() => {
if (!isInElement) {
document.documentElement.style.height = "auto";
document.body.style.height = "auto";
document.documentElement.style.overflow = "auto";
}
});
setContext(eventsTrackerContextKey, eventsTracker);
onMount(async () => {
if (productId === null) {
handleError(
new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"Product ID was not set before purchase.",
),
);
return;
}
if (!customerEmail) {
currentPage = "email-entry";
} else {
currentPage = "payment-entry-loading";
handleCheckoutStart();
}
});
const handleCheckoutStart = () => {
if (!customerEmail) {
handleError(
new PurchaseFlowError(PurchaseFlowErrorCode.MissingEmailError),
);
return;
}
if (priceBreakdown.taxCollectionEnabled) {
priceBreakdown.taxCalculationStatus = "loading";
}
purchaseOperationHelper
.checkoutStart(
appUserId,
productId,
purchaseOption,
rcPackage.webBillingProduct.presentedOfferingContext,
customerEmail,
metadata,
)
.then((result) => {
lastError = null;
currentPage = "payment-entry";
gatewayParams = result.gateway_params;
})
.then(async (result) => {
if (priceBreakdown.taxCollectionEnabled) {
await refreshTaxCalculation();
}
return result;
})
.catch((e: PurchaseFlowError) => {
handleError(e);
});
};
const handleContinue = (params: ContinueHandlerParams = {}) => {
if (params.error) {
handleError(params.error);
return;
}
if (currentPage === "email-entry") {
if (params.authInfo) {
customerEmail = params.authInfo.email;
currentPage = "email-entry-processing";
}
handleCheckoutStart();
return;
}
if (currentPage === "payment-entry") {
currentPage = "payment-entry-processing";
purchaseOperationHelper
.pollCurrentPurchaseForCompletion()
.then((pollResult) => {
currentPage = "success";
redemptionInfo = pollResult.redemptionInfo;
operationSessionId = pollResult.operationSessionId;
})
.catch((error: PurchaseFlowError) => {
handleError(error);
});
return;
}
if (currentPage === "success" || currentPage === "error") {
onFinished(operationSessionId!, redemptionInfo);
return;
}
currentPage = "success";
};
async function refreshTaxCalculation(
taxCustomerDetails: TaxCustomerDetails | undefined = undefined,
) {
// TODO: Handle tax calculation errors including:
// - missing state
// - missing postal code
// - generic
// - unexpected error
priceBreakdown.taxCalculationStatus = "loading";
const taxCalculation = await purchaseOperationHelper.checkoutCalculateTax(
taxCustomerDetails?.countryCode,
taxCustomerDetails?.postalCode,
);
priceBreakdown.taxCalculationStatus = "calculated";
priceBreakdown.totalAmountInMicros = taxCalculation.total_amount_in_micros;
priceBreakdown.taxAmountInMicros = taxCalculation.tax_amount_in_micros;
priceBreakdown.totalExcludingTaxInMicros =
taxCalculation.total_excluding_tax_in_micros;
priceBreakdown.taxBreakdown =
taxCalculation.pricing_phases.base.tax_breakdown;
priceBreakdown.pendingReason = null;
gatewayParams.elements_configuration =
taxCalculation.gateway_params.elements_configuration;
}
const handleError = (e: PurchaseFlowError) => {
const event = createCheckoutFlowErrorEvent({
errorCode: e.getErrorCode().toString(),
errorMessage: e.message,
});
eventsTracker.trackSDKEvent(event);
if (currentPage === "email-entry-processing" && e.isRecoverable()) {
lastError = e;
currentPage = "email-entry";
return;
}
lastError = e;
currentPage = "error";
};
const closeWithError = () => {
onError(
lastError ??
new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
"Unknown error without state set.",
),
);
};
</script>
<PurchasesUiInner
isSandbox={purchases.isSandbox()}
currentPage={currentPage as CurrentPage}
{brandingInfo}
{productDetails}
purchaseOptionToUse={purchaseOption}
{handleContinue}
{lastError}
{gatewayParams}
{purchaseOperationHelper}
{closeWithError}
{isInElement}
{onClose}
{priceBreakdown}
onTaxCustomerDetailsUpdated={refreshTaxCalculation}
/>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/colors.ts | TypeScript | import type { BrandingAppearance } from "../../entities/branding";
/**
* All those colors get translated in --rc-color-<property_name> css variables.
* i.e. --rc-color-error or --rc-color-input-background
*/
export interface Colors {
error: string;
warning: string;
focus: string;
accent: string;
primary: string;
"primary-hover": string;
"primary-pressed": string;
"primary-text": string;
white: string;
"grey-text-dark": string;
"grey-text-light": string;
"grey-ui-dark": string;
"grey-ui-light": string;
"input-background": string;
background: string;
}
export const DEFAULT_FORM_COLORS: Colors = {
error: "#B0171F",
warning: "#f4e971",
focus: "#1148B8",
accent: "#767676",
primary: "#576CDB",
"primary-hover": "rgba(87, 108, 219, .8)",
"primary-pressed": "rgba(87, 108, 219, .9)",
"primary-text": "#ffffff",
white: "#ffffff",
"grey-text-dark": "rgba(0,0,0,1)",
"grey-text-light": "rgba(0,0,0,0.7)",
"grey-ui-dark": "rgba(0,0,0,0.3)",
"grey-ui-light": "rgba(0,0,0,0.1)",
"input-background": "white",
background: "white",
};
export const DEFAULT_INFO_COLORS: Colors = {
error: "#B0171F",
warning: "#f4e971",
focus: "#1148B8",
accent: "#767676",
primary: "#576CDB",
"primary-hover": "rgba(87, 108, 219, .8)",
"primary-pressed": "rgba(87, 108, 219, .9)",
"primary-text": "#ffffff",
white: "#ffffff",
"grey-text-dark": "rgba(0,0,0,1)",
"grey-text-light": "rgba(0,0,0,0.7)",
"grey-ui-dark": "rgba(0,0,0,0.3)",
"grey-ui-light": "rgba(0,0,0,0.1)",
"input-background": "white",
background: "#EFF3FA",
};
/**
* Mappings from the colors defined above and the colors downloaded from the BrandingAppearance.
* Bear in mind that font colors are calculated dynamically given the resulting background color.
*/
export const ColorsToBrandingAppearanceMapping: Record<
string,
keyof BrandingAppearance
> = {
error: "color_error",
focus: "color_accent",
accent: "color_accent",
primary: "color_buttons_primary",
};
export const FormColorsToBrandingAppearanceMapping = {
...ColorsToBrandingAppearanceMapping,
"input-background": "color_form_bg",
background: "color_form_bg",
};
export const InfoColorsToBrandingAppearanceMapping = {
...ColorsToBrandingAppearanceMapping,
"input-background": "color_product_info_bg",
background: "color_product_info_bg",
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/constants.ts | TypeScript | export const PaywallDefaultContainerZIndex = 1000001;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/shapes.ts | TypeScript | export interface Shape {
"input-border-radius": string;
"input-button-border-radius": string;
}
export const RoundedShape: Shape = {
"input-border-radius": "4px",
"input-button-border-radius": "8px",
};
export const RectangularShape: Shape = {
"input-border-radius": "0px",
"input-button-border-radius": "0px",
};
export const PillsShape: Shape = {
"input-border-radius": "12px",
"input-button-border-radius": "9999px",
};
export const DefaultShape = RoundedShape;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/spacing.ts | TypeScript | export interface Spacing {
[key: string]: {
mobile: string;
tablet: string;
desktop: string;
};
}
export const DEFAULT_SPACING: Spacing = {
outerPadding: {
mobile: "clamp(1.3125rem, 5.6vw, 1.5rem)",
tablet: "clamp(1.40625rem, 7.52vw, 3.25rem)",
desktop: "clamp(1.5rem, 9.44vw, 5rem)",
},
outerPaddingSmall: {
mobile: "clamp(0.75rem, 4.2vw, 1rem)",
tablet: "clamp(0.75rem, 4.2vw, 1rem)",
desktop: "clamp(1.5rem, 9.44vw, 5rem)",
},
gapSmall: {
mobile: "0.25rem",
tablet: "0.375rem",
desktop: "0.375rem",
},
gapMedium: {
mobile: "0.5rem",
tablet: "0.75rem",
desktop: "0.75rem",
},
gapLarge: {
mobile: "0.75rem",
tablet: "0.75rem",
desktop: "0.75rem",
},
gapXLarge: {
mobile: "1rem",
tablet: "1.5rem",
desktop: "1.5rem",
},
gapXXLarge: {
mobile: "1.25rem",
tablet: "2.25rem",
desktop: "2.25rem",
},
gapXXXLarge: {
mobile: "2.25rem",
tablet: "4.5rem",
desktop: "4.5rem",
},
inputHeight: {
mobile: "3rem",
tablet: "3rem",
desktop: "3rem",
},
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/text.ts | TypeScript | /**
* All text styles get translated into --rc-text-<property_name> CSS variables.
* i.e., --rc-text-title1-font-size or --rc-text-title1-line-height
*/
interface TextStyle {
fontSize: string;
lineHeight: string;
fontWeight: string;
}
export interface TextStyles {
[key: string]: {
mobile: TextStyle;
desktop: TextStyle;
};
}
export const DEFAULT_FONT_FAMILY =
"-apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif";
export const DEFAULT_TEXT_STYLES: TextStyles = {
titleXXLarge: {
desktop: { fontSize: "32px", lineHeight: "140%", fontWeight: "500" },
mobile: { fontSize: "28px", lineHeight: "140%", fontWeight: "500" },
},
titleXLarge: {
desktop: { fontSize: "36px", lineHeight: "140%", fontWeight: "500" },
mobile: { fontSize: "24px", lineHeight: "140%", fontWeight: "500" },
},
titleLarge: {
desktop: { fontSize: "28px", lineHeight: "140%", fontWeight: "500" },
mobile: { fontSize: "20px", lineHeight: "140%", fontWeight: "500" },
},
titleMedium: {
desktop: { fontSize: "24px", lineHeight: "140%", fontWeight: "500" },
mobile: { fontSize: "17px", lineHeight: "140%", fontWeight: "500" },
},
// sm font on figma
body1: {
desktop: { fontSize: "16px", lineHeight: "140%", fontWeight: "400" },
mobile: { fontSize: "16px", lineHeight: "140%", fontWeight: "400" },
},
caption: {
desktop: { fontSize: "14px", lineHeight: "140%", fontWeight: "400" },
mobile: { fontSize: "12px", lineHeight: "140%", fontWeight: "400" },
},
largeCaption: {
desktop: { fontSize: "14px", lineHeight: "140%", fontWeight: "400" },
mobile: { fontSize: "14px", lineHeight: "140%", fontWeight: "400" },
},
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/theme.ts | TypeScript | import {
toFormColors,
toFormStyleVar,
toProductInfoStyleVar,
toShape,
toSpacingVars,
toTextStyleVar,
} from "./utils";
import type { Shape } from "./shapes";
import type { Colors } from "./colors";
import { DEFAULT_TEXT_STYLES } from "./text";
import { DEFAULT_SPACING } from "./spacing";
import type { BrandingAppearance } from "../../entities/branding";
export class Theme {
private readonly brandingAppearance: BrandingAppearance | null | undefined;
constructor(brandingAppearance?: BrandingAppearance | null | undefined) {
if (brandingAppearance) {
this.brandingAppearance = brandingAppearance;
} else {
this.brandingAppearance = undefined;
}
}
get shape(): Shape {
return toShape(this.brandingAppearance);
}
get formColors(): Colors {
return toFormColors(this.brandingAppearance);
}
get formStyleVars() {
return toFormStyleVar(this.brandingAppearance);
}
get productInfoStyleVars() {
return toProductInfoStyleVar(this.brandingAppearance);
}
get spacing() {
return DEFAULT_SPACING;
}
get textStyles() {
return DEFAULT_TEXT_STYLES;
}
get textStyleVars() {
return toTextStyleVar("text", this.textStyles);
}
get spacingStyleVars() {
return toSpacingVars("spacing", this.spacing);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/theme/utils.ts | TypeScript | import {
type Colors,
DEFAULT_FORM_COLORS,
DEFAULT_INFO_COLORS,
FormColorsToBrandingAppearanceMapping,
InfoColorsToBrandingAppearanceMapping,
} from "./colors";
import {
DefaultShape,
PillsShape,
RectangularShape,
RoundedShape,
type Shape,
} from "./shapes";
import { DEFAULT_FONT_FAMILY, type TextStyles } from "./text";
import type { Spacing } from "./spacing";
import type { BrandingAppearance } from "../../entities/branding";
type RGB = {
r: number;
g: number;
b: number;
};
const hexToRGB = (color: string): RGB | null => {
if (color.length == 7)
return {
r: parseInt(color.slice(1, 3), 16),
g: parseInt(color.slice(3, 5), 16),
b: parseInt(color.slice(5, 7), 16),
};
if (color.length == 4)
return {
r: parseInt(color[1], 16),
g: parseInt(color[2], 16),
b: parseInt(color[3], 16),
};
return null;
};
const isLightColor = ({
r,
g,
b,
luminanceThreshold,
}: RGB & {
luminanceThreshold: number;
}) => {
// Gamma correction
const gammaCorrect = (color: number) => {
color = color / 255;
return color <= 0.03928
? color / 12.92
: Math.pow((color + 0.055) / 1.055, 2.4);
};
// Calculate relative luminance with gamma correction
const luminance =
0.2126 * gammaCorrect(r) +
0.7152 * gammaCorrect(g) +
0.0722 * gammaCorrect(b);
// Return whether the background is light
return luminance > luminanceThreshold;
};
export const DEFAULT_LUMINANCE_THRESHOLD = 0.37;
const rgbToTextColors = (
rgb: RGB,
luminanceThreshold: number = DEFAULT_LUMINANCE_THRESHOLD,
) => {
const baseColor = isLightColor({ ...rgb, luminanceThreshold })
? "0,0,0"
: "255,255,255";
return {
"grey-text-dark": `rgb(${baseColor})`,
"grey-text-light": `rgba(${baseColor},0.70)`,
"grey-ui-dark": `rgba(${baseColor},0.3)`,
"grey-ui-light": `rgba(${baseColor},0.1)`,
};
};
function overlayColor(
baseColor: string,
overlay: string,
alpha: number,
): string {
const base = hexToRGB(baseColor) || { r: 0, g: 0, b: 0 };
const over = hexToRGB(overlay) || { r: 255, g: 255, b: 255 };
const r = Math.round(over.r * alpha + base.r * (1 - alpha));
const g = Math.round(over.g * alpha + base.g * (1 - alpha));
const b = Math.round(over.b * alpha + base.b * (1 - alpha));
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
/**
* Applies an alpha value to a color.
* If the base color is light, the overlay color is black.
* If the base color is dark, the overlay color is white.
*/
export function applyAlpha(baseColor: string, alpha: number): string {
const defaultRgb = { r: 255, g: 255, b: 255 };
const normalizedAlpha = Math.max(0, Math.min(1, alpha));
let appliedBaseColor = baseColor;
let baseRgb = hexToRGB(baseColor) || defaultRgb;
if (isNaN(baseRgb.r) || isNaN(baseRgb.g) || isNaN(baseRgb.b)) {
baseRgb = defaultRgb;
appliedBaseColor = "#FFFFFF";
}
const baseIsLight = isLightColor({
...baseRgb,
luminanceThreshold: DEFAULT_LUMINANCE_THRESHOLD,
});
const overlay = baseIsLight ? "#000000" : "#FFFFFF";
return overlayColor(appliedBaseColor, overlay, normalizedAlpha);
}
function toHex(val: number) {
return val.toString(16).padStart(2, "0").toUpperCase();
}
const textColorsForBackground = (
backgroundColor: string,
primaryColor: string,
defaultColors: Colors,
luminanceThreshold: number = DEFAULT_LUMINANCE_THRESHOLD,
) => {
const textColors = {
"grey-text-dark": defaultColors["grey-text-dark"],
"grey-text-light": defaultColors["grey-text-light"],
"grey-ui-dark": defaultColors["grey-ui-dark"],
"grey-ui-light": defaultColors["grey-ui-light"],
"primary-text": defaultColors["primary-text"],
};
// Find the text colors for the background
if (backgroundColor?.startsWith("#")) {
const rgb = hexToRGB(backgroundColor);
if (rgb !== null) {
Object.assign(textColors, rgbToTextColors(rgb));
}
}
// Find the text color for the primary color
if (primaryColor?.startsWith("#")) {
const rgb = hexToRGB(primaryColor);
if (rgb !== null) {
textColors["primary-text"] = isLightColor({ ...rgb, luminanceThreshold })
? "black"
: "white";
}
}
return textColors;
};
const colorsForButtonStates = (primaryColor: string) => {
return {
"primary-hover": applyAlpha(primaryColor, 0.1),
"primary-pressed": applyAlpha(primaryColor, 0.15),
};
};
const fallback = <T>(
somethingNullable: T | null | undefined,
defaultValue: T,
): T => {
return somethingNullable ? somethingNullable : defaultValue;
};
const mapColors = (
colorsMapping: Record<string, string>,
defaultColors: Colors,
brandingAppearance?: BrandingAppearance | null | undefined,
): Colors => {
const mappedColors = Object.entries(colorsMapping).map(([target, source]) => [
target,
fallback(
brandingAppearance
? brandingAppearance[source as keyof BrandingAppearance]
: null,
defaultColors[target as keyof Colors],
),
]);
return Object.fromEntries(mappedColors) as Colors;
};
export const toColors = (
colorsMapping: Record<string, string>,
defaultColors: Colors,
brandingAppearance?: BrandingAppearance | null | undefined,
): Colors => {
const mappedColors = mapColors(
colorsMapping,
defaultColors,
brandingAppearance,
);
return brandingAppearance
? {
...defaultColors,
...mappedColors,
...textColorsForBackground(
mappedColors.background,
mappedColors.primary,
defaultColors,
),
...colorsForButtonStates(mappedColors.primary),
}
: { ...defaultColors }; //copy, do not reference.
};
export const toProductInfoColors = (
brandingAppearance?: BrandingAppearance | null | undefined,
): Colors => {
return toColors(
InfoColorsToBrandingAppearanceMapping,
DEFAULT_INFO_COLORS,
brandingAppearance,
);
};
export const toFormColors = (
brandingAppearance?: BrandingAppearance | null | undefined,
): Colors => {
return toColors(
FormColorsToBrandingAppearanceMapping,
DEFAULT_FORM_COLORS,
brandingAppearance,
);
};
export const toShape = (
brandingAppearance?: BrandingAppearance | null | undefined,
): Shape => {
if (!brandingAppearance) {
return DefaultShape;
}
switch (brandingAppearance.shapes) {
case "rounded":
return RoundedShape;
case "rectangle":
return RectangularShape;
case "pill":
return PillsShape;
default:
return DefaultShape;
}
};
export const toStyleVar = (prefix: string = "", entries: [string, string][]) =>
entries.map(([key, value]) => `--rc-${prefix}-${key}: ${value}`).join("; ");
/**
* Assigns values to the css variables given the branding appearance customization.
* @param appearance BrandingAppearance
* @return a style parameter compatible string.
*/
export const toProductInfoStyleVar = (
appearance?: BrandingAppearance | null,
) => {
const colorVariablesString = toStyleVar(
"color",
Object.entries(toProductInfoColors(appearance)),
);
const shapeVariableString = toStyleVar(
"shape",
Object.entries(toShape(appearance)),
);
return [colorVariablesString, shapeVariableString].join("; ");
};
/**
* Assigns values to the css variables given the branding appearance customization.
* @param appearance BrandingAppearance
* @return a style parameter compatible string.
*/
export const toFormStyleVar = (appearance?: BrandingAppearance | null) => {
const colorVariablesString = toStyleVar(
"color",
Object.entries(toFormColors(appearance)),
);
const shapeVariableString = toStyleVar(
"shape",
Object.entries(toShape(appearance)),
);
return [colorVariablesString, shapeVariableString].join("; ");
};
/**
* Convert text styles into CSS variables for both desktop and mobile.
*/
export const toTextStyleVar = (prefix: string = "", textStyles: TextStyles) =>
Object.entries(textStyles)
.flatMap(([key, { desktop, mobile }]) => [
`--rc-${prefix}-${key}-desktop: normal normal ${desktop.fontWeight} ${desktop.fontSize}/${desktop.lineHeight} ${DEFAULT_FONT_FAMILY}`,
`--rc-${prefix}-${key}-mobile: normal normal ${mobile.fontWeight} ${mobile.fontSize}/${mobile.lineHeight} ${DEFAULT_FONT_FAMILY}`,
`--rc-${prefix}-${key}-desktop-font-size: ${desktop.fontSize}`,
`--rc-${prefix}-${key}-mobile-font-size: ${mobile.fontSize}`,
])
.join("; ");
/**
* Generates CSS variables for the spacing system.
*/
export const toSpacingVars = (prefix: string = "", spacing: Spacing) =>
Object.entries(spacing)
.map(
([key, { mobile, tablet, desktop }]) =>
`--rc-${prefix}-${key}-mobile: ${mobile}; --rc-${prefix}-${key}-tablet: ${tablet}; --rc-${prefix}-${key}-desktop: ${desktop};`,
)
.join(" ");
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/types/payment-element-error.ts | TypeScript | export enum PaymentElementErrorCode {
ErrorLoadingStripe = 0,
HandledFormSubmissionError = 1,
UnhandledFormSubmissionError = 2,
}
export type PaymentElementError = {
code: PaymentElementErrorCode;
gatewayErrorCode: string | undefined;
message: string | undefined;
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/ui/ui-types.ts | TypeScript | import type { TaxBreakdown } from "../networking/responses/checkout-calculate-tax-response";
import type { PurchaseFlowError } from "../helpers/purchase-operation-helper";
export type CurrentPage =
| "email-entry"
| "email-entry-processing"
| "payment-entry-loading"
| "payment-entry"
| "payment-entry-processing"
| "success"
| "error";
export type ContinueHandlerParams = {
authInfo?: { email: string };
error?: PurchaseFlowError;
};
export type TaxCalculationStatus = "pending" | "loading" | "calculated";
export type TaxCalculationPendingReason =
| "needs_postal_code"
| "needs_state_or_postal_code";
export type PriceBreakdown = {
currency: string;
totalAmountInMicros: number;
taxCollectionEnabled: boolean;
totalExcludingTaxInMicros: number;
taxCalculationStatus: TaxCalculationStatus | null;
pendingReason: TaxCalculationPendingReason | null;
taxAmountInMicros: number | null;
taxBreakdown: TaxBreakdown[] | null;
};
export type TaxCustomerDetails = {
countryCode: string | undefined;
postalCode: string | undefined;
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
svelte.config.js | JavaScript | import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
export default {
preprocess: [
vitePreprocess({
style: {
postcss: true,
},
}),
],
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
test.html | HTML | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RCBilling Example</title>
<script src="./dist/rcbilling-js.iife.js"></script>
<style>
/* Some basic styling for our Stripe form */
#payment-form {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="payment-form"></div>
<script>
document.addEventListener("DOMContentLoaded", function () {
var billing = new RCBilling(
"web_tFpmIVwEGKNprbMOyiRRzZAbzIHX",
"test_rcbilling",
);
setTimeout(() => {
billing.renderForm(
document.getElementById("payment-form"),
"monthly.product_1234",
);
}, 3000);
});
</script>
</body>
</html>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
vite.config.js | JavaScript | import { fileURLToPath } from "url";
import { dirname, resolve } from "path";
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
import { svelte } from "@sveltejs/vite-plugin-svelte";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, "src/main.ts"),
name: "Purchases",
fileName: (format) => `Purchases.${format}.js`,
},
},
plugins: [
dts({
rollupTypes: true,
}),
svelte({ compilerOptions: { css: "injected" } }),
],
});
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
vitest.config.js | JavaScript | import { configDefaults, defineConfig } from "vitest/config";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { svelteTesting } from "@testing-library/svelte/vite";
export default defineConfig(() => ({
plugins: [
svelte({
compilerOptions: {
css: "injected",
},
preprocess: {
style: ({ content }) => {
return { code: content };
},
},
}),
svelteTesting(),
],
// This is needed to make test pass after adding decorators in Purchases.
esbuild: { target: "es2022" },
// Use the test field to define test-specific configurations
test: {
// Set the environment to 'jsdom' to simulate a browser environment
environment: "jsdom",
// Set globals that your tests might depend on
globals: true,
// If you're using TypeScript
// You may need to set up Vite to handle TypeScript files
// This will depend on your project's setup
transformMode: {
web: [/.[tj]sx?$/], // RegEx to transform TypeScript and JavaScript files
},
// Specify reporters if needed (e.g., verbose, dot, json)
reporters: "default", // 'default' or an array of reporters
// If you need to extend the default jsdom environment (e.g., with a URL)
setupFiles: "./vitest.setup.js", // Path to the setup file
// Coverage configuration if you are collecting test coverage
coverage: {
provider: "istanbul", // or 'c8'
// Additional coverage configuration options...
},
// Other configurations like shims for APIs or polyfills can also be included
// ...
exclude: [...configDefaults.exclude, "examples/**"],
},
define: {
"process.env.VITEST": JSON.stringify(true),
},
// If you need to define other Vite configurations, they can go here
// ...
}));
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
vitest.setup.js | JavaScript | // Or configuring DOM elements that your app expects on startup
document.body.innerHTML = `<div id="app"></div>`;
if (!Element.prototype.animate) {
Element.prototype.animate = () => ({
cancel: () => {},
play: () => {},
pause: () => {},
finish: () => {},
});
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
vitest.shims.d.ts | TypeScript | /// <reference types="@vitest/browser/providers/playwright" /> | yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
vitest.workspace.js | JavaScript | import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineWorkspace } from "vitest/config";
import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
const dirname =
typeof __dirname !== "undefined"
? // eslint-disable-next-line no-undef
__dirname
: path.dirname(fileURLToPath(import.meta.url));
// More info at: https://storybook.js.org/docs/writing-tests/test-addon
export default defineWorkspace([
"vitest.config.js",
{
extends: "vite.config.js",
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/writing-tests/test-addon#storybooktest
storybookTest({ configDir: path.join(dirname, ".storybook") }),
],
test: {
name: "storybook",
browser: {
enabled: true,
headless: true,
provider: "playwright",
instances: [{ browser: "chromium" }],
},
setupFiles: [".storybook/vitest.setup.ts"],
},
},
]);
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
cmd/dstp/dstp.go | Go | package main
import (
"context"
flag "github.com/spf13/pflag"
"fmt"
"os"
"path/filepath"
"github.com/ycd/dstp/config"
"github.com/ycd/dstp/pkg/dstp"
)
func main() {
fs := flag.NewFlagSet(filepath.Base(os.Args[0]), flag.ExitOnError)
// Configure the options from the flags/config file
opts, err := config.ConfigureOptions(fs, os.Args[1:])
if err != nil {
config.UsageAndExit(err)
}
ctx := context.Background()
err = dstp.RunAllTests(ctx, *opts)
if err != nil {
fmt.Print(err)
os.Exit(1)
}
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
config/config.go | Go | package config
import (
flag "github.com/spf13/pflag"
"fmt"
"os"
"github.com/fatih/color"
)
type Config struct {
Addr string
Output string
PingCount int
Timeout int
ShowHelp bool
Port string
CustomDnsServer string
}
var usageStr = `Usage: dstp [OPTIONS] [ARGS]
Options:
-a, --addr <string> The URL or the IP address to run tests against [REQUIRED]
-o, --out <string> The type of the output, either json or plaintext [Default: plaintext]
-p <int> Number of ping packets [Default: 3]
-t <int> Give up on ping after this many seconds [Default: 2s per ping packet]
--port <string> Port for testing TLS and HTTPS connectivity [Default: 443]
--dns <string> Custom DNS server to use for DNS resolution [No default]
-h, --help Show this message and exit.
`
// UsageAndExit prints usage and exists the program.
func UsageAndExit(err error) {
color.Red(err.Error())
fmt.Printf(usageStr)
os.Exit(1)
}
// HelpAndExit , prints helps and exists the program.
func HelpAndExit() {
fmt.Printf(usageStr)
os.Exit(0)
}
// ConfigureOptions is a helper function for parsing options
func ConfigureOptions(fs *flag.FlagSet, args []string) (*Config, error) {
opts := &Config{}
// Define flags
fs.StringVar(&opts.Addr, "a", "", "The URL or the IP address to run tests against")
fs.StringVar(&opts.Addr, "addr", "", "The URL or the IP address to run tests against")
fs.StringVar(&opts.Output, "o", "plaintext", "The type of the output")
fs.StringVar(&opts.Output, "out", "plaintext", "The type of the output")
fs.StringVar(&opts.Port, "port", "", "Port for testing TLS and HTTPS connectivity")
fs.IntVar(&opts.PingCount, "p", 3, "Number of ping packets")
fs.IntVar(&opts.Timeout, "t", -1, "Give up on ping after this many seconds")
fs.StringVar(&opts.CustomDnsServer, "dns", "", "Custom DNS server to use for DNS resolution")
fs.BoolVar(&opts.ShowHelp, "h", false, "Show help message")
fs.BoolVar(&opts.ShowHelp, "help", false, "Show help message")
if err := fs.Parse(args); err != nil {
return nil, err
}
values := fs.Args()
if opts.ShowHelp {
HelpAndExit()
}
if !opts.ShowHelp && len(values) < 1 && opts.Addr == "" {
HelpAndExit()
}
if opts.Addr == "" {
if len(values) >= 1 {
opts.Addr = values[0]
} else {
return nil, fmt.Errorf("address cannot be empty")
}
}
return opts, nil
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/common/color.go | Go | package common
import "github.com/fatih/color"
// Bunch of pre-defined coloring functions
var (
Yellow = color.New(color.FgYellow).SprintFunc()
Red = color.New(color.FgRed).SprintFunc()
Green = color.New(color.FgGreen).SprintFunc()
Blue = color.New(color.FgBlue).SprintFunc()
Magenta = color.New(color.FgMagenta).SprintFunc()
Cyan = color.New(color.FgCyan).SprintFunc()
White = color.New(color.FgHiWhite).SprintFunc()
)
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/common/types.go | Go | package common
import (
"encoding/json"
"fmt"
"reflect"
"sync"
)
type Args []string
type Address string
type ResultPart struct {
Content string
Error error
}
func (o ResultPart) String() string {
if o.Error != nil {
return Red(o.Error.Error())
}
return o.Content
}
func (a Address) String() string {
return string(a)
}
type Result struct {
Ping ResultPart `json:"ping"`
DNS ResultPart `json:"dns"`
SystemDNS ResultPart `json:"system_dns"`
TLS ResultPart `json:"tls"`
HTTPS ResultPart `json:"https"`
Mu sync.Mutex `json:"-"`
}
func (r Result) Output(outputType string) string {
var output string
switch outputType {
case "plaintext":
v := reflect.ValueOf(r)
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Name == "Mu" {
continue
}
output += fmt.Sprintf("%s: %v\n", White(v.Type().Field(i).Name), Green(v.Field(i).Interface()))
}
case "json":
v := map[string]string{}
if r.Ping.Content != "" {
v["ping"] = r.Ping.Content
}
if r.DNS.Content != "" {
v["dns"] = r.DNS.Content
}
if r.SystemDNS.Content != "" {
v["system_dns"] = r.SystemDNS.Content
}
if r.TLS.Content != "" {
v["tls"] = r.TLS.Content
}
if r.HTTPS.Content != "" {
v["https"] = r.HTTPS.Content
}
byt, _ := json.MarshalIndent(v, "", " ")
output += string(byt)
}
return output
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/addr.go | Go | package dstp
import (
"fmt"
"net"
"net/url"
"strings"
)
func getAddr(addr string) (string, error) {
var pu string
// Cleanup the scheme first
//
// [scheme:][//[userinfo@]host][/]path[?query][#fragment]
for _, prefix := range []string{"https://", "http://"} {
if strings.HasPrefix(addr, prefix) {
addr = strings.ReplaceAll(addr, prefix, "")
}
}
ip := net.ParseIP(addr)
if ip == nil {
// This case is only for URL's
// add a scheme for conform go's url form
addr = "https://" + addr
parsedURL, err := url.ParseRequestURI(addr)
if err != nil {
u, err := url.ParseRequestURI(addr)
if err != nil {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return "", fmt.Errorf("failed to split host and port")
}
uu, err := url.ParseRequestURI(host)
if err != nil {
return "", fmt.Errorf("failed to parse url: %v", err.Error())
}
pu = uu.Hostname()
} else {
pu = u.Host
}
} else {
// If URI doesn't have any slash in it, the first part is considered as scheme
if parsedURL.Hostname() == "" {
pu = parsedURL.Scheme
} else {
pu = parsedURL.Hostname()
}
}
} else {
pu = addr
}
return pu, nil
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/addr_test.go | Go | package dstp
import (
"testing"
)
func TestGetAddr(t *testing.T) {
tests := []struct {
addrs []string
}{
{
addrs: []string{
"facebook.com",
"facebook.com:80",
"https://jvns.ca",
"https://jvns.ca:443",
"8.8.8.8",
"2606:4700:3031::ac43:b35a",
"meta.stackoverflow.com:443",
"https://meta.stackoverflow.com/",
},
},
}
for _, tt := range tests {
for _, addr := range tt.addrs {
a, _ := getAddr(addr)
if a == "" {
t.Fatalf("address parsing failed for: %v", addr)
}
}
}
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/dstp.go | Go | package dstp
import (
"context"
"crypto/tls"
"fmt"
"math"
"net"
"net/http"
"sync"
"time"
"github.com/ycd/dstp/config"
"github.com/ycd/dstp/pkg/common"
"github.com/ycd/dstp/pkg/lookup"
"github.com/ycd/dstp/pkg/ping"
)
// RunAllTests executes all the tests against the given domain, IP or DNS server.
func RunAllTests(ctx context.Context, config config.Config) error {
var result common.Result
addr, err := getAddr(config.Addr)
if err != nil {
return err
}
if config.Timeout == -1 {
config.Timeout = 2 * config.PingCount
}
var wg sync.WaitGroup
wg.Add(5)
go ping.RunTest(ctx, &wg, common.Address(addr), config.PingCount, config.Timeout, &result)
go ping.RunDNSTest(ctx, &wg, common.Address(addr), config.PingCount, config.Timeout, &result)
go lookup.Host(ctx, &wg, common.Address(addr), config.CustomDnsServer, &result)
go testTLS(ctx, &wg, common.Address(addr), config.Timeout, config.Port, &result)
go testHTTPS(ctx, &wg, common.Address(addr), config.Timeout, config.Port, &result)
wg.Wait()
s := result.Output(config.Output)
printWithColor(s)
return nil
}
func testTLS(ctx context.Context, wg *sync.WaitGroup, address common.Address, t int, port string, result *common.Result) error {
var output string
defer wg.Done()
p := "443"
if port != "" {
p = port
}
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: time.Duration(t) * time.Second}, "tcp", fmt.Sprintf("%s:%s", string(address), p), nil)
if err != nil {
result.Mu.Lock()
result.TLS = common.ResultPart{
Error: err,
}
result.Mu.Unlock()
return err
}
err = conn.VerifyHostname(string(address))
if err != nil {
result.Mu.Lock()
result.TLS = common.ResultPart{
Error: err,
}
result.Mu.Unlock()
return err
}
notAfter := conn.ConnectionState().PeerCertificates[0].NotAfter
expiresAfter := time.Until(notAfter)
expiry := math.Round(expiresAfter.Hours() / 24)
if expiry > 0 {
output += fmt.Sprintf("certificate is valid for %v more days", expiry)
} else {
output += fmt.Sprintf("the certificate expired %v days ago", -expiry)
}
result.Mu.Lock()
result.TLS = common.ResultPart{
Content: output,
}
result.Mu.Unlock()
return nil
}
func testHTTPS(ctx context.Context, wg *sync.WaitGroup, address common.Address, t int, port string, result *common.Result) error {
defer wg.Done()
url := fmt.Sprintf("https://%s", address.String())
if port != "" {
url += fmt.Sprintf(":%s", port)
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
result.Mu.Lock()
result.HTTPS = common.ResultPart{
Error: err,
}
result.Mu.Unlock()
return err
}
client := http.Client{
Timeout: time.Second * time.Duration(t),
}
resp, err := client.Do(req)
if err != nil {
result.Mu.Lock()
result.HTTPS = common.ResultPart{
Error: err,
}
result.Mu.Unlock()
return err
}
result.Mu.Lock()
result.HTTPS = common.ResultPart{
Content: fmt.Sprintf("got %s", resp.Status),
}
result.Mu.Unlock()
return nil
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/dstp_test.go | Go | //go:build integration
package dstp
import (
"context"
"testing"
"github.com/ycd/dstp/config"
)
func TestRunAllTests(t *testing.T) {
ctx := context.Background()
c := config.Config{
Addr: "https://jvns.ca",
Output: "plaintext",
ShowHelp: false,
Timeout: 3,
PingCount: 3,
}
c1 := config.Config{
Addr: "8.8.8.8",
Output: "plaintext",
ShowHelp: false,
Timeout: 3,
PingCount: 3,
}
c2 := config.Config{
Addr: "facebook.com",
Output: "plaintext",
ShowHelp: false,
Timeout: 3,
PingCount: 3,
}
c3 := config.Config{
Addr: "https://meta.stackoverflow.com/",
Output: "plaintext",
ShowHelp: false,
Timeout: 3,
PingCount: 3,
}
c4 := config.Config{
Addr: "facebook.com:80",
Output: "plaintext",
ShowHelp: false,
Timeout: 3,
PingCount: 3,
}
for _, conf := range []config.Config{c, c1, c2, c3, c4} {
if err := RunAllTests(ctx, conf); err != nil {
t.Fatal(err.Error())
}
}
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/dstp_unix.go | Go | //go:build !windows
package dstp
import (
"fmt"
)
func printWithColor(s string) {
fmt.Print(s)
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/dstp/dstp_windows.go | Go | package dstp
import (
"fmt"
"github.com/fatih/color"
)
func printWithColor(s string) {
// https://pkg.go.dev/github.com/fatih/color@v1.13.0#readme-insert-into-noncolor-strings-sprintfunc
fmt.Fprint(color.Output, s)
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/lookup/host.go | Go | package lookup
import (
"context"
"net"
"strings"
"sync"
"github.com/ycd/dstp/pkg/common"
)
func Host(ctx context.Context, wg *sync.WaitGroup, addr common.Address, customDnsServer string, result *common.Result) error {
defer wg.Done()
part := common.ResultPart{}
r := &net.Resolver{}
if customDnsServer != "" {
customDnsServer = formatDNSServer(customDnsServer)
r = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{}
return d.DialContext(ctx, "udp", customDnsServer)
},
}
}
addrs, err := r.LookupHost(ctx, addr.String())
if err != nil {
part.Error = err
result.SystemDNS = part
return err
}
part.Content = "resolving " + strings.Join(addrs, ", ")
result.SystemDNS = part
return nil
}
func formatDNSServer(server string) string {
if server == "" {
return server
}
// If port is already specified, return as-is
if _, _, err := net.SplitHostPort(server); err == nil {
return server
}
// Append default DNS port
return net.JoinHostPort(server, "53")
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/lookup/host_test.go | Go | //go:build integration || darwin
package lookup
import (
"context"
"sync"
"testing"
"github.com/ycd/dstp/pkg/common"
)
func TestLookup(t *testing.T) {
var wg sync.WaitGroup
var result common.Result
wg.Add(1)
err := Host(context.Background(), &wg, common.Address("jvns.ca"), "8.8.8.8", &result)
if err != nil {
t.Fatal(err)
}
wg.Wait()
if result.DNS.Error != nil {
t.Fatal(result.DNS.Error)
}
if result.SystemDNS.Content == "" {
t.Fatal("System DNS resolution failed")
}
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/ping/dns.go | Go | package ping
import (
"context"
"fmt"
"sync"
"time"
"github.com/ycd/dstp/pkg/common"
)
func RunDNSTest(ctx context.Context, wg *sync.WaitGroup, addr common.Address, count int, timeout int, result *common.Result) error {
defer wg.Done()
part := common.ResultPart{}
pinger, err := createPinger(addr.String())
if err != nil {
part.Error = err
result.Mu.Lock()
result.DNS = part
result.Mu.Unlock()
return err
}
pinger.Count = count
pinger.Timeout = time.Duration(timeout) * time.Second
err = pinger.Run()
if err != nil {
part.Error = fmt.Errorf("failed to run ping: %v", err.Error())
result.Mu.Lock()
result.DNS = part
result.Mu.Unlock()
return err
}
part.Content = "resolving " + pinger.IPAddr().String()
result.Mu.Lock()
result.DNS = part
result.Mu.Unlock()
return nil
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/ping/ping.go | Go | package ping
import (
"bufio"
"bytes"
"context"
"fmt"
"log"
"os/exec"
"runtime"
"strings"
"sync"
"time"
"github.com/ycd/dstp/pkg/common"
)
func RunTest(ctx context.Context, wg *sync.WaitGroup, addr common.Address, count int, timeout int, result *common.Result) error {
return runPing(ctx, wg, addr, count, timeout, result)
}
func runPing(ctx context.Context, wg *sync.WaitGroup, addr common.Address, count int, timeout int, result *common.Result) error {
var output common.ResultPart
defer wg.Done()
pinger, err := createPinger(addr.String())
if err != nil {
return err
}
pinger.Count = count
pinger.Timeout = time.Duration(timeout) * time.Second
err = pinger.Run()
if err != nil {
if out, err := runPingFallback(ctx, addr, count); err == nil {
output = common.ResultPart{
Content: out.String(),
}
} else {
err := fmt.Errorf("failed to run ping: %v", err.Error())
result.Mu.Lock()
result.Ping = common.ResultPart{
Error: err,
}
result.Mu.Unlock()
return err
}
} else {
stats := pinger.Statistics()
if stats.PacketsRecv == 0 {
if out, err := runPingFallback(ctx, addr, count); err == nil {
output = common.ResultPart{
Content: out.String(),
}
} else {
output = common.ResultPart{
Error: fmt.Errorf("no response"),
}
}
} else {
output = common.ResultPart{
Content: joinS(joinC(stats.AvgRtt.String())),
}
}
}
result.Mu.Lock()
result.Ping = output
result.Mu.Unlock()
return nil
}
// runPingFallback executes the ping command from cli
// Currently fallback is not implemented for windows.
func runPingFallback(ctx context.Context, addr common.Address, count int) (common.ResultPart, error) {
args := fmt.Sprintf("-c %v", count)
command := fmt.Sprintf("ping %s %s", args, addr.String())
// This is not handled because the ping
// writes the output to stdout whether it fails or not
out, err := executeCommand(command)
po, err := parsePingOutput(out)
if err != nil {
return common.ResultPart{Error: err}, err
}
return common.ResultPart{
Content: po.AvgRTT + "ms",
}, nil
}
func executeCommand(command string) (string, error) {
var errb bytes.Buffer
var out string
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/C", command)
} else {
cmd = exec.Command("/bin/bash", "-c", command)
}
cmd.Stderr = &errb
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("got error while tracing pipe: %v", err)
}
err = cmd.Start()
if err != nil {
return "", err
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
out += scanner.Text() + "\n"
}
if err := cmd.Wait(); err != nil {
return out, fmt.Errorf("got error: %v, stderr: %v", err, errb.String())
}
return out, nil
}
type pingOutput struct {
PacketLoss string
PacketReceived string
PacketTransmitted string
MinRTT string
AvgRTT string
MaxRTT string
}
var (
RequestTimeoutError = fmt.Errorf("requests timed out")
PacketLossError = fmt.Errorf("timeout error: 100.0%% packet loss")
)
// parsePingOutput parses the output of ping by parsing the stdout
// example output:
//
// ping -c 3 jvns.ca
// PING jvns.ca (104.21.91.206): 56 data bytes
// 64 bytes from 104.21.91.206: icmp_seq=0 ttl=58 time=14.468 ms
// 64 bytes from 104.21.91.206: icmp_seq=1 ttl=58 time=14.450 ms
// 64 bytes from 104.21.91.206: icmp_seq=2 ttl=58 time=14.683 ms
//
// --- jvns.ca ping statistics ---
// 3 packets transmitted, 3 packets received, 0.0% packet loss
// round-trip min/avg/max/stddev = 14.450/14.534/14.683/0.106 ms
func parsePingOutput(out string) (pingOutput, error) {
var po pingOutput
lines := strings.Split(out, "\n")
for _, line := range lines {
switch {
case strings.Contains(line, "packets transmitted"):
arr := strings.Split(line, ",")
if len(arr) < 3 {
continue
}
po.PacketTransmitted, po.PacketReceived, po.PacketLoss = arr[0], arr[1], arr[2]
case strings.Contains(line, "min/avg/max"):
l := strings.ReplaceAll(line, " = ", " ")
arr := strings.Split(l, " ")
if len(arr) != 4 {
continue
}
rttArr := strings.Split(arr[2], "/")
if len(rttArr) != 4 {
continue
}
po.MinRTT, po.AvgRTT, po.MaxRTT = rttArr[0], rttArr[1], rttArr[2]
}
}
if po.MinRTT == "" && po.AvgRTT == "" && po.MaxRTT == "" {
return po, RequestTimeoutError
}
if po.PacketLoss == "100.0% packet loss" {
return po, PacketLossError
}
return po, nil
}
func joinC(args ...string) string {
return strings.Join(args, ",")
}
func joinS(args ...string) string {
return strings.Join(args, " ")
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/ping/ping_test.go | Go | //go:build integration || darwin || fallback
package ping
import (
"context"
"fmt"
"github.com/ycd/dstp/pkg/common"
"testing"
)
func TestPingFallback(t *testing.T) {
out, err := runPingFallback(context.Background(), common.Address("8.8.8.8"), 3)
if err != nil {
t.Fatal(err.Error())
}
fmt.Println(out.String())
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/ping/ping_unix.go | Go | //go:build !windows
package ping
import (
"github.com/go-ping/ping"
)
func createPinger(addr string) (*ping.Pinger, error) {
p, err := ping.NewPinger(addr)
return p, err
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
pkg/ping/ping_windows.go | Go | //go:build windows
package ping
import (
"github.com/go-ping/ping"
)
func createPinger(addr string) (*ping.Pinger, error) {
p, err := ping.NewPinger(addr)
// https://pkg.go.dev/github.com/go-ping/ping#readme-windows
p.SetPrivileged(true)
return p, err
}
| ycd/dstp | 1,294 | 🧪 Run common networking tests against any site. | Go | ycd | Yagiz Degirmenci | |
src/api/handlers.rs | Rust | use std::{net::Ipv4Addr, str::FromStr, sync::Mutex};
use actix_web::{get, post, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use crate::{IpAndPath, Memory};
#[derive(Serialize)]
struct Health<T>
where
T: Into<String>,
{
status: T,
}
#[get("/health")]
pub async fn get_health() -> HttpResponse {
HttpResponse::Ok()
.content_type("application/json")
.json(Health { status: "ok" })
}
#[derive(Serialize)]
struct LimitResponse {
allowed: bool,
metadata: Metadata,
}
#[derive(Serialize)]
struct Metadata {
id: u64,
x_ratelimit_remaning: i32,
x_ratelimit_limit: u32,
path: Option<String>,
ip: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
id: u64,
path: Option<String>,
ip: Option<String>,
}
#[derive(Serialize)]
pub struct BadRequest {
error: String,
}
#[post("/request")]
pub async fn new_request(
payload: web::Json<Request>,
data: web::Data<Mutex<crate::Dur<Memory>>>,
) -> impl Responder {
let mut _data = data.lock().unwrap();
let ip_addr: Option<Ipv4Addr> = match payload.ip {
None => None,
Some(ref v) => match Ipv4Addr::from_str(v) {
Ok(ip) => Some(ip),
Err(_) => {
return HttpResponse::BadRequest()
.json(BadRequest {
error: format!("invalid ip address: {}", v),
})
.with_header("X-Ratelimit-Limit", _data.config.limit() as usize)
}
},
};
let request = _data.request(payload.id, IpAndPath::new(ip_addr, payload.path.clone()));
let remaning_requests: i32 = _data.config.limit() as i32 - request.1 as i32;
HttpResponse::Ok()
.json(LimitResponse {
allowed: request.0,
metadata: Metadata {
x_ratelimit_remaning: remaning_requests,
x_ratelimit_limit: _data.config.limit(),
id: payload.id,
path: payload.path.clone(),
ip: payload.ip.clone(),
},
})
.with_header("X-Ratelimit-Remaning", remaning_requests as usize)
.with_header("X-Ratelimit-Limit", _data.config.limit() as usize)
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/api/mod.rs | Rust | mod handlers;
pub use handlers::{get_health, new_request};
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/backend/backend.rs | Rust | use std::{error::Error, net::Ipv4Addr, time::Duration};
use super::IpAndPath;
// Use the selected backend for storing related information
// about the API.
pub trait Backend {
fn new() -> Self;
fn clear(&mut self);
fn evict_older_timestamps(&mut self, id: u64, timestamp: Duration, window_time: u16);
fn insert(&mut self, id: u64, ip_and_path: IpAndPath) -> Result<usize, Box<dyn Error>>;
fn len(&self) -> usize;
fn request_count(&self, id: u64) -> usize;
fn ip_address_count(&self, id: u64, ip: Ipv4Addr) -> usize;
fn path_count(&self, id: u64, path: String) -> usize;
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/backend/memory.rs | Rust | use std::{
collections::HashMap,
error::Error,
net::Ipv4Addr,
time::{Duration, SystemTime},
};
use crate::Backend;
// In memory baceknd for dur
#[derive(Debug, Clone)]
pub struct Memory {
record: HashMap<u64, HashMap<Duration, IpAndPath>>,
}
#[derive(Debug, Clone)]
pub struct IpAndPath {
pub ip: Option<Ipv4Addr>,
pub path: Option<String>,
}
impl IpAndPath {
pub fn new(ip: Option<Ipv4Addr>, path: Option<String>) -> Self {
Self { ip: ip, path: path }
}
pub fn from_ip_addr(ip: Ipv4Addr) -> Self {
Self {
ip: Some(ip),
path: None,
}
}
pub fn from_path(path: String) -> Self {
Self {
ip: None,
path: Some(path),
}
}
}
impl Backend for Memory {
fn new() -> Self {
Self {
record: HashMap::new(),
}
}
// inserts the incoming request to the
fn insert(&mut self, id: u64, ip_and_path: IpAndPath) -> Result<usize, Box<dyn Error>> {
let key = self.record.entry(id).or_insert(HashMap::new());
key.insert(
SystemTime::now().duration_since(std::time::UNIX_EPOCH)?,
ip_and_path,
);
Ok(key.len())
}
fn clear(&mut self) {
self.record.clear();
}
fn len(&self) -> usize {
self.record.len()
}
// Get the current request count of the id
fn request_count(&self, id: u64) -> usize {
match self.record.get(&id) {
None => 0,
Some(v) => v.len(),
}
}
fn evict_older_timestamps(&mut self, id: u64, timestamp: Duration, window_time: u16) {
match self.record.get_mut(&id) {
Some(logs) => {
for (duration, _) in logs.clone().iter() {
if (timestamp.as_secs() - duration.as_secs()) > window_time as u64 {
logs.remove(duration);
}
}
}
None => return,
}
}
fn ip_address_count(&self, id: u64, ip: Ipv4Addr) -> usize {
match self.record.get(&id) {
Some(v) => v
.iter()
.filter(|(_, ip_and_path)| match ip_and_path.ip.clone() {
Some(addr) => addr == ip,
None => false,
})
.count(),
None => 0,
}
}
fn path_count(&self, id: u64, path: String) -> usize {
match self.record.get(&id) {
Some(v) => v
.iter()
.filter(|(_, ip_and_path)| match ip_and_path.path.clone() {
Some(_path) => _path == path,
None => false,
})
.count(),
None => 0,
}
}
}
#[cfg(test)]
mod tests {
use std::net::Ipv4Addr;
use super::*;
#[test]
fn test_insert() {
let mut mem = Memory::new();
assert!(mem.insert(1234859, IpAndPath::new(None, None)).is_ok());
}
#[test]
fn test_insert_multiple() {
let mut mem = Memory::new();
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
}
#[test]
fn test_len_and_cleanup() {
let mut mem = Memory::new();
assert_eq!(mem.len(), 0);
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
mem.clear();
assert_eq!(mem.len(), 0);
}
#[test]
fn test_request_count() {
let mut mem = Memory::new();
assert_eq!(mem.len(), 0);
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12348591, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12384, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12384, IpAndPath::new(None, None)).is_ok());
assert!(mem.insert(12384, IpAndPath::new(None, None)).is_ok());
assert_eq!(mem.request_count(12348591), 5);
assert_eq!(mem.request_count(12384), 3);
mem.clear();
assert_eq!(mem.len(), 0);
assert_eq!(mem.request_count(12348591), 0);
assert_eq!(mem.request_count(12384), 0);
}
#[test]
fn test_unique_ip_addresses() {
let mut mem = Memory::new();
assert_eq!(mem.len(), 0);
assert!(mem
.insert(
12348591,
IpAndPath::from_ip_addr(Ipv4Addr::new(127, 0, 0, 1))
)
.is_ok());
assert!(mem
.insert(
12348591,
IpAndPath::from_ip_addr(Ipv4Addr::new(127, 0, 0, 1))
)
.is_ok());
assert!(mem
.insert(
12348591,
IpAndPath::from_ip_addr(Ipv4Addr::new(127, 0, 0, 1))
)
.is_ok());
assert!(mem
.insert(
12348591,
IpAndPath::from_ip_addr(Ipv4Addr::new(127, 0, 0, 1))
)
.is_ok());
assert!(mem
.insert(
12348591,
IpAndPath::from_ip_addr(Ipv4Addr::new(127, 0, 0, 1))
)
.is_ok());
// assert_eq!(mem.unique_ip_addresses(12348591), 5);
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/backend/mod.rs | Rust | mod backend;
mod memory;
pub use backend::Backend;
pub use memory::IpAndPath;
pub use memory::Memory;
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/client.rs | Rust | use std::{net::Ipv4Addr, str::FromStr};
pub use clap::{App, Arg};
use crate::{
config::{Ip, Limits, Path},
Config,
};
static NAME: &str = "dur";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static ABOUT: &str =
"dur, lightweight, stateless, configurable rate limiter with extremely high-performance";
#[allow(dead_code)]
mod options {
pub const CONFIG_PATH: &str = "config-path";
pub const PORT: &str = "port";
pub const HOST: &str = "host";
pub const LIMIT: &str = "limit";
pub const WINDOW_TIME: &str = "window-time";
pub const IP_ADDR_LIMIT: &str = "ipaddr-limit";
pub const PATHS: &str = "paths";
pub const PATH_LIMIT: &str = "path-limit";
pub const PATH_WINDOW_TIME: &str = "path-window-time";
pub const IP_ADDRESSES: &str = "ip-addresses";
pub const IP_ADDRESSES_LIMIT: &str = "ip-addresses-limit";
pub const IP_ADDRESSES_WINDOW_TIME: &str = "ip-addresses-window-time";
}
pub fn cli() -> Config {
let matches = App::new(NAME)
.name(NAME)
.version(VERSION)
.about(ABOUT)
.arg(
Arg::with_name(options::CONFIG_PATH)
.short("c")
.long(options::CONFIG_PATH)
.help("path to config file")
.takes_value(true)
.value_name("PATH"),
)
.arg(
Arg::with_name(options::PORT)
.short("p")
.long(options::PORT)
.help("Bind socket to this port.")
.default_value("8000")
.takes_value(true)
.value_name("PORT"),
)
.arg(
Arg::with_name(options::HOST)
.short("h")
.long(options::HOST)
.help("Bind socket to this host.")
.default_value("127.0.0.1")
.takes_value(true)
.value_name("HOST"),
)
.arg(
Arg::with_name(options::LIMIT)
.short("L")
.long(options::LIMIT)
.help("The maximum number of requests to allow inside a window")
.default_value("300")
.value_name("INT")
.takes_value(true),
)
.arg(
Arg::with_name(options::WINDOW_TIME)
.long(options::WINDOW_TIME)
.help("The window time, in seconds")
.default_value("100")
.value_name("INT")
.takes_value(true),
)
.arg(
Arg::with_name(options::IP_ADDR_LIMIT)
.long(options::IP_ADDR_LIMIT)
.help("The maximum number of requests to allow from specified ip addresses")
.default_value("5")
.value_name("INT")
.takes_value(true),
)
.arg(
Arg::with_name(options::PATHS)
.short("P")
.long(options::PATHS)
.help("Paths to be specifically limited, with comma seperated values")
.value_name("PATH,PATH...")
.takes_value(true)
.require_delimiter(true),
)
.arg(
Arg::with_name(options::PATH_LIMIT)
.long(options::PATH_LIMIT)
.help("The maximum number of requests to allow in specified paths")
.requires(options::PATHS)
.value_name("INT")
.takes_value(true)
.default_value_if(options::PATHS, None, "300"),
)
.arg(
Arg::with_name(options::PATH_WINDOW_TIME)
.long(options::PATH_WINDOW_TIME)
.help("The window time for paths, in seconds")
.requires(options::PATHS)
.value_name("INT")
.takes_value(true),
)
.arg(
Arg::with_name(options::IP_ADDRESSES)
.short("I")
.long(options::IP_ADDRESSES)
.help("IP Addresses to be specifically limited, with comma seperated values")
.value_name("IP,IP...")
.takes_value(true)
.require_delimiter(true),
)
.arg(
Arg::with_name(options::IP_ADDRESSES_LIMIT)
.long(options::IP_ADDRESSES_LIMIT)
.help("The maximum number of requests to allow in specified IP addresses")
.requires(options::PATHS)
.value_name("INT")
.takes_value(true)
.default_value_if(options::IP_ADDRESSES, None, "300"),
)
.arg(
Arg::with_name(options::IP_ADDRESSES_WINDOW_TIME)
.long(options::IP_ADDRESSES_WINDOW_TIME)
.help("The window time for IP addresses, in seconds")
.requires(options::IP_ADDRESSES)
.value_name("INT")
.takes_value(true),
)
.get_matches();
let limit = matches
.value_of(options::LIMIT)
.unwrap()
.parse::<u32>()
.unwrap();
let ip_addr_limit = matches
.value_of(options::IP_ADDR_LIMIT)
.unwrap()
.parse::<u16>()
.unwrap();
let window_time = matches
.value_of(options::WINDOW_TIME)
.unwrap()
.parse::<u16>()
.unwrap();
let limits: Limits = {
let path: Option<Path> = match matches.values_of(options::PATHS) {
Some(v) => {
let vals: Vec<String> = v.map(String::from).collect();
let path_window_time = matches
.value_of(options::PATH_WINDOW_TIME)
.unwrap_or("300")
.parse::<u16>()
.unwrap();
let path_limit = matches
.value_of(options::PATH_LIMIT)
.unwrap_or("0")
.parse::<u32>()
.unwrap();
Some(Path::new(vals, path_limit, path_window_time))
}
None => None,
};
let ip: Option<Ip> = match matches.values_of(options::IP_ADDRESSES) {
Some(v) => {
let vals: Vec<Ipv4Addr> = v
.map(|s| match Ipv4Addr::from_str(s) {
Ok(addr) => addr,
Err(e) => panic!("bad ip address: {}", e),
})
.collect();
let ip_window_time = matches
.value_of(options::IP_ADDRESSES_WINDOW_TIME)
.unwrap_or("300")
.parse::<u16>()
.unwrap();
let ip_limit = matches
.value_of(options::IP_ADDRESSES_LIMIT)
.unwrap_or("0")
.parse::<u32>()
.unwrap();
Some(Ip::new(vals, ip_limit, ip_window_time))
}
None => None,
};
Limits::new(path, ip)
};
let port = matches.value_of(options::PORT).unwrap().to_owned();
let host = matches.value_of(options::HOST).unwrap().to_owned();
match matches.value_of(options::CONFIG_PATH) {
Some(path) => Config::from_path(path.to_owned()),
None => Config::new(
Some(limit),
Some(ip_addr_limit),
Some(window_time),
Some(port),
Some(host),
limits,
),
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/config/config.rs | Rust | use std::net::Ipv4Addr;
use serde::Deserialize;
use super::{Ip, Path};
#[derive(Debug, Clone, Deserialize)]
pub struct Config {
// The maximum limit for a user with the given id
// can send maximum request in a single period.
limit: u32,
// Maximum count of unique IP addresses
// that the same user can send requests from
// in a single period.
ip_addr_limit: u16,
// Window time in seconds.
window_time: u16,
port: Option<String>,
host: Option<String>,
limits: Option<Limits>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Limits {
path: Option<Path>,
ip: Option<Ip>,
}
impl Limits {
pub fn new(path: Option<Path>, ip: Option<Ip>) -> Self {
Self { path: path, ip: ip }
}
fn empty() -> Self {
Self {
path: None,
ip: None,
}
}
}
impl Config {
pub fn new(
limit: Option<u32>,
ip_addr_limit: Option<u16>,
window_time: Option<u16>,
port: Option<String>,
host: Option<String>,
limits: Limits,
) -> Self {
Self {
limit: limit.unwrap_or(50 as u32),
ip_addr_limit: ip_addr_limit.unwrap_or(16 as u16),
window_time: window_time.unwrap_or(300 as u16),
port: Some(port.unwrap_or("8000".to_owned())),
host: Some(host.unwrap_or("127.0.0.1".to_owned())),
limits: Some(limits),
}
}
pub fn limit(&self) -> u32 {
self.limit
}
pub fn set_limit(&mut self, limit: u32) -> u32 {
self.limit = limit;
self.limit
}
pub fn ip_addr_limit(&self) -> u16 {
self.ip_addr_limit
}
pub fn set_ip_addr_limit(&mut self, limit: u16) -> u16 {
self.ip_addr_limit = limit;
self.ip_addr_limit
}
pub fn window_time(&self) -> u16 {
self.window_time
}
pub fn set_window_time(&mut self, window_time: u16) -> u16 {
self.window_time = window_time;
self.window_time
}
pub fn host_and_port(&self) -> String {
let host_and_port = vec![self.host.clone().unwrap(), self.port.clone().unwrap()];
host_and_port.join(":").to_owned()
}
pub(crate) fn limits_is_some(&self) -> bool {
self.limits.is_some()
}
pub fn limit_path_is_some(&self) -> bool {
if self.limits_is_some() {
return self.limits.as_ref().unwrap().path.is_some();
}
false
}
pub fn limit_ip_is_some(&self) -> bool {
if self.limits_is_some() {
return self.limits.as_ref().unwrap().ip.is_some();
}
false
}
pub fn limited_paths(&self) -> Option<Vec<String>> {
if self.limit_path_is_some() {
return self.limits.as_ref().unwrap().path.as_ref().unwrap().paths();
}
None
}
pub fn path_limit(&self) -> Option<u32> {
if self.limit_path_is_some() {
return self.limits.as_ref().unwrap().path.as_ref().unwrap().limit();
}
None
}
pub fn path_window_time(&self) -> Option<u16> {
if self.limit_path_is_some() {
return self
.limits
.as_ref()
.unwrap()
.path
.as_ref()
.unwrap()
.window_time();
}
None
}
pub fn limited_ip_addresses(&self) -> Option<Vec<Ipv4Addr>> {
if self.limit_ip_is_some() {
return self
.limits
.as_ref()
.unwrap()
.ip
.as_ref()
.unwrap()
.ip_addresses();
}
None
}
pub fn ip_addresses_limit(&self) -> Option<u32> {
if self.limit_ip_is_some() {
return self.limits.as_ref().unwrap().ip.as_ref().unwrap().limit();
}
None
}
pub fn ip_addresses_window_time(&self) -> Option<u16> {
if self.limit_ip_is_some() {
return self
.limits
.as_ref()
.unwrap()
.ip
.as_ref()
.unwrap()
.window_time();
}
None
}
}
impl Default for Config {
fn default() -> Self {
Self {
limit: 50 as u32,
ip_addr_limit: 5 as u16,
window_time: 300 as u16,
host: Some("127.0.0.1".to_owned()),
port: Some("8000".to_owned()),
limits: Some(Limits::empty()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_updating_window_log() {
let mut config = Config::default();
assert!(config.limit() == 50);
assert!(config.ip_addr_limit() == 5);
assert!(config.window_time() == 300);
config.set_window_time(500);
config.set_limit(100);
config.set_ip_addr_limit(25);
assert!(config.window_time() == 500);
assert!(config.limit() == 100);
assert!(config.ip_addr_limit() == 25);
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/config/ip.rs | Rust | use std::net::Ipv4Addr;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct Ip {
ip_addresses: Option<Vec<Ipv4Addr>>,
limit: Option<u32>,
window_time: Option<u16>,
}
impl Ip {
#[allow(dead_code)]
pub fn new<I, T>(ip_addrs: I, limit: u32, window_time: u16) -> Self
where
T: Into<Ipv4Addr>,
I: IntoIterator<Item = T>,
{
Self {
ip_addresses: Some(ip_addrs.into_iter().map(Into::into).collect()),
limit: Some(limit),
window_time: Some(window_time),
}
}
pub fn ip_addresses(&self) -> Option<Vec<Ipv4Addr>> {
self.ip_addresses.clone()
}
pub fn window_time(&self) -> Option<u16> {
self.window_time
}
pub fn limit(&self) -> Option<u32> {
self.limit
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_new() {
let ip = Ip::new(
vec![
Ipv4Addr::new(127, 0, 0, 1),
Ipv4Addr::new(154, 10, 94, 111),
Ipv4Addr::new(10, 51, 144, 201),
],
300,
400,
);
assert_eq!(
ip.ip_addresses.clone().unwrap()[0],
Ipv4Addr::new(127, 0, 0, 1)
);
assert_eq!(
ip.ip_addresses.clone().unwrap()[1],
Ipv4Addr::new(154, 10, 94, 111)
);
assert_eq!(
ip.ip_addresses.clone().unwrap()[2],
Ipv4Addr::new(10, 51, 144, 201)
);
assert_eq!(ip.limit, Some(300));
assert_eq!(ip.window_time, Some(400));
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/config/mod.rs | Rust | mod config;
mod ip;
mod parser;
mod path;
pub use config::{Config, Limits};
pub use ip::Ip;
pub use path::Path;
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/config/parser.rs | Rust | use std::{fs::File, io::Read};
use crate::Config;
impl Config {
pub fn from_path(path: String) -> Self {
let mut file = File::open(path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let config: Config = toml::from_str(&contents).unwrap();
println!("{:#?}", config);
config
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/config/path.rs | Rust | use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct Path {
paths: Option<Vec<String>>,
limit: Option<u32>,
window_time: Option<u16>,
}
impl Path {
#[allow(dead_code)]
pub fn new<I, T>(endpoints: I, limit: u32, window_time: u16) -> Self
where
T: Into<String>,
I: IntoIterator<Item = T>,
{
Self {
paths: Some(endpoints.into_iter().map(Into::into).collect()),
limit: Some(limit),
window_time: Some(window_time),
}
}
pub fn paths(&self) -> Option<Vec<String>> {
self.paths.clone()
}
pub fn window_time(&self) -> Option<u16> {
self.window_time
}
pub fn limit(&self) -> Option<u32> {
self.limit
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_new() {
let path = Path::new(vec!["test", "1234", "214141"], 300, 400);
assert_eq!(path.paths.clone().unwrap()[0], "test".to_owned());
assert_eq!(path.paths.clone().unwrap()[1], "1234".to_owned());
assert_eq!(path.paths.clone().unwrap()[2], "214141".to_owned());
assert_eq!(path.limit, Some(300));
assert_eq!(path.window_time, Some(400));
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/dur.rs | Rust | use std::time::SystemTime;
use crate::{Backend, Config, IpAndPath};
#[derive(Debug, Clone)]
pub struct Dur<T> {
backend: T,
pub config: Config,
}
impl<T> Dur<T>
where
T: Backend,
{
pub fn new(backend: T, config: Option<Config>) -> Self {
Self {
backend: backend,
config: config.unwrap_or_default(),
}
}
pub fn request(&mut self, id: u64, ip_and_path: IpAndPath) -> (bool, usize) {
match self.backend.insert(id, ip_and_path.clone()) {
Ok(v) => {
let current_timestamp = SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap();
self.backend.evict_older_timestamps(
id,
current_timestamp,
self.config.window_time(),
);
let mut allow = true;
if (v as u32) > self.config.limit() {
allow = false
}
match self.config.limited_ip_addresses() {
// TODO(ycd): properly test here.
Some(ip_addrs) => match ip_and_path.ip {
Some(ref ip) => {
if ip_addrs.contains(&ip.clone()) {
match self.config.ip_addresses_limit() {
Some(limit) => {
if (limit as usize)
< self.backend.ip_address_count(id, ip.clone())
{
allow = false
}
}
None => (),
}
}
}
None => (),
},
None => (),
}
match self.config.limited_paths() {
Some(paths) => match ip_and_path.path {
Some(path) => {
if paths.contains(&path.clone()) {
match self.config.path_limit() {
Some(limit) => {
if (limit as usize) < self.backend.path_count(id, path) {
allow = false
}
}
None => (),
}
}
}
None => (),
},
None => (),
}
(allow, v)
}
Err(why) => {
eprintln!("an error occured: {}", why);
(false, 0)
}
}
}
pub fn remaning_requests(&self, id: u64) -> u32 {
self.backend.request_count(id) as u32
}
}
#[cfg(test)]
mod tests {
use std::thread::sleep;
use super::*;
use crate::Memory;
#[test]
fn test_sliding_window_logs() {
let mut dur = Dur::new(Memory::new(), None);
dur.config.set_window_time(1);
dur.request(12938102, IpAndPath::new(None, None));
dur.request(12938102, IpAndPath::new(None, None));
dur.request(12938102, IpAndPath::new(None, None));
dur.request(12938102, IpAndPath::new(None, None));
dur.request(12938102, IpAndPath::new(None, None));
dur.request(12938102, IpAndPath::new(None, None));
assert_eq!(dur.backend.request_count(12938102), 6);
sleep(std::time::Duration::from_secs(4));
dur.request(12938102, IpAndPath::new(None, None));
assert_eq!(dur.backend.request_count(12938102), 1);
}
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/helpers.rs | Rust | use actix_web::{web::Json, ResponseError};
use serde::Serialize;
/// Helper function to reduce boilerplate of an OK/Json response
#[allow(dead_code)]
pub fn respond_json<T>(data: T) -> Result<Json<T>, Box<dyn ResponseError>>
where
T: Serialize,
{
Ok(Json(data))
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/main.rs | Rust | mod api;
mod backend;
mod client;
mod config;
mod dur;
mod helpers;
use std::sync::Mutex;
pub use backend::{Backend, IpAndPath, Memory};
pub use config::Config;
use actix_web::{web, App, HttpServer};
pub use dur::Dur;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let config = client::cli();
let data = web::Data::new(Mutex::new(Dur::new(Memory::new(), Some(config.clone()))));
eprintln!("dur is running on: {}", &config.host_and_port());
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.service(api::get_health)
.service(api::new_request)
})
.bind(&config.host_and_port())?
.run()
.await
}
| ycd/dur | 15 | 📮 Lightweight, high performance and configurable API rate limiter. | Rust | ycd | Yagiz Degirmenci | |
src/main.rs | Rust | mod rotator;
use std::process::exit;
use clap::{App, Arg};
use rotator::rotator::Rotator;
fn main() {
// Set level filter to minimum to log everything.
log::set_max_level(log::LevelFilter::Debug);
let matches = App::new("rotator")
.version("0.1")
.author("Yagiz Degirmenci. <yagizcanilbey1903@gmail.com>")
.about("Rotate IPv6 addresses")
.arg(
Arg::new("interface")
.short('i')
.long("interface")
.value_name("INTERFACE")
.about("Set a network device interface (Example: eth0, ens33)")
.required(true)
.takes_value(true),
)
.arg(
Arg::new("network")
.short('n')
.long("network")
.value_name("ADDRESS")
.about("Address prefix to rotate over. (Example: 2001:db8:0000:0000)")
.required(true)
.takes_value(true),
)
.arg(
Arg::new("count")
.short('c')
.long("count")
.value_name("COUNT")
.about("Number of the addresses to be routed")
.default_value("5")
.takes_value(true),
)
.arg(
Arg::new("block")
.short('b')
.long("block")
.value_name("CIDR block")
.about("block range to rotate (Example: 32, 48, 64)")
.default_value("64")
.takes_value(true),
)
.arg(
Arg::new("sleep")
.short('s')
.long("sleep")
.about("Rotate to a new IP in x seconds")
.takes_value(true)
.default_value("10"),
)
.get_matches();
// interface is a device actually, used as device "internally".
let device = matches.value_of("interface").unwrap();
let sleep = matches
.value_of("sleep")
.unwrap()
.parse::<u16>()
.expect("time is not a valid integer");
let count = matches
.value_of("count")
.unwrap()
.parse::<u16>()
.expect("count is not a valid integer");
let block = match matches.value_of("block").unwrap().parse::<u8>() {
Ok(b) => match b {
32 => rotator::rotator::IpBlock::CIDR32,
48 => rotator::rotator::IpBlock::CIDR48,
64 => rotator::rotator::IpBlock::CIDR64,
_ => {
eprintln!("[ERROR] {} is an invalid CIDR block", b);
exit(1)
}
},
Err(why) => panic!("invalid CIDR block: {:?}", why),
};
let network = matches.value_of("network").unwrap();
let mut rotator = Rotator::builder()
.device(device)
.network(network)
.count(count)
.block(block)
.sleep_time(sleep)
.build();
&rotator.rotate();
}
| ycd/ipv6-rotator | 22 | :twisted_rightwards_arrows: Rotate over ::/32 - ::/48 - ::/64 CIDR block of IPv6 addresses by randomly generating them. | Rust | ycd | Yagiz Degirmenci | |
src/rotator/mod.rs | Rust | pub mod rotator;
| ycd/ipv6-rotator | 22 | :twisted_rightwards_arrows: Rotate over ::/32 - ::/48 - ::/64 CIDR block of IPv6 addresses by randomly generating them. | Rust | ycd | Yagiz Degirmenci | |
src/rotator/rotator.rs | Rust | use std::{io::Stderr, process::exit, thread::sleep};
use rand::prelude::SliceRandom;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum IpBlock {
CIDR32,
CIDR48,
CIDR64,
}
#[derive(Debug, PartialEq)]
pub struct Rotator<'a> {
pub device: &'a str,
pub sleep_time: u16,
pub block: IpBlock,
pub network: &'a str,
pub count: u16,
addresses: Box<Vec<String>>,
available_chars: Vec<String>,
}
impl<'a> Rotator<'a> {
pub fn builder() -> Self {
Self {
device: "",
sleep_time: 10,
block: IpBlock::CIDR64,
network: "",
count: 5,
addresses: Box::new(Vec::new()),
available_chars: vec![
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f",
]
.iter()
.map(|s| s.to_string())
.collect(),
}
}
// Set the ip block
pub fn block(&mut self, block: IpBlock) -> &mut Self {
self.block = block;
self
}
pub fn network(&mut self, network: &'a str) -> &mut Self {
self.network = network;
self
}
pub fn sleep_time(&mut self, sleep_time: u16) -> &mut Self {
self.sleep_time = sleep_time;
self
}
pub fn device(&mut self, device: &'a str) -> &mut Self {
self.device = device;
self
}
pub fn count(&mut self, count: u16) -> &mut Self {
self.count = count;
self
}
pub fn build(&mut self) -> Self {
Self {
block: self.block,
count: self.count,
device: self.device,
network: self.network,
sleep_time: self.sleep_time,
addresses: Box::new(self.addresses.to_vec()),
available_chars: vec![
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f",
]
.iter()
.map(|s| s.to_string())
.collect(),
}
}
}
impl Rotator<'_> {
pub fn rotate(&mut self) {
loop {
for _ in 0..self.count {
self.add_ip().unwrap();
}
sleep(std::time::Duration::from_secs(self.sleep_time as u64));
self.cleanup_addresses().unwrap();
}
}
pub fn generate_ip(&mut self) -> String {
match self.block {
IpBlock::CIDR32 => format!(
"{}:{}:{}:{}:{}:{}:{}/{}",
&self.network,
self.gen(),
self.gen(),
self.gen(),
self.gen(),
self.gen(),
self.gen(),
"32"
),
IpBlock::CIDR48 => format!(
"{}:{}:{}:{}:{}:{}/{}",
&self.network,
self.gen(),
self.gen(),
self.gen(),
self.gen(),
self.gen(),
"48"
),
IpBlock::CIDR64 => format!(
"{}:{}:{}:{}:{}/{}",
&self.network,
self.gen(),
self.gen(),
self.gen(),
self.gen(),
"64"
),
}
}
fn gen(&self) -> String {
vec![
self.available_chars
.choose(&mut rand::thread_rng())
.unwrap(),
self.available_chars
.choose(&mut rand::thread_rng())
.unwrap(),
self.available_chars
.choose(&mut rand::thread_rng())
.unwrap(),
self.available_chars
.choose(&mut rand::thread_rng())
.unwrap(),
]
.iter()
.flat_map(|s| s.chars())
.collect()
}
pub fn add_ip(&mut self) -> Result<(), Stderr> {
let new_ip = self.generate_ip();
self.addresses.push(new_ip.clone());
let _ = match std::process::Command::new("ip")
.arg("-6")
.arg("addr")
.arg("add")
.arg(&new_ip)
.arg("dev")
.arg(&self.device)
.output()
{
Ok(_) => println!("[ADD] {}", &new_ip),
Err(why) => {
println!("[ERROR] unable to add new ip addr: {}", why);
exit(1)
}
};
Ok(())
}
/// Delete all the addresses that is inside addresses
pub fn cleanup_addresses(&mut self) -> Result<(), Stderr> {
self.addresses.iter().for_each(|addr| {
match std::process::Command::new("ip")
.arg("-6")
.arg("addr")
.arg("del")
.arg(addr)
.arg("dev")
.arg(&self.device)
.output()
{
Ok(_) => {
println!("[DEL] {}", &addr);
}
Err(why) => {
eprintln!("[ERROR] unable to delete ip addr({}): {}", &addr, why);
exit(1)
}
}
});
self.addresses.clear();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_success_test() {
let rotator = self::Rotator::builder()
.device("eth0")
.network("2001:db8:0000:0000")
.count(5)
.block(IpBlock::CIDR48)
.sleep_time(15)
.build();
assert_eq!(
self::Rotator {
device: "eth0",
network: "2001:db8:0000:0000",
count: 5,
block: IpBlock::CIDR48,
sleep_time: 15,
addresses: Box::new(Vec::new()),
available_chars: vec![
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f",
]
.iter()
.map(|s| s.to_string())
.collect()
},
rotator
);
}
#[test]
fn test_unique_ip() {}
}
| ycd/ipv6-rotator | 22 | :twisted_rightwards_arrows: Rotate over ::/32 - ::/48 - ::/64 CIDR block of IPv6 addresses by randomly generating them. | Rust | ycd | Yagiz Degirmenci | |
examples/main.py | Python | import ortoml
as_dict = {"test": "val", "test1": {"another": "dict"}}
# convert dict to toml string
as_toml = ortoml.dumps(as_dict)
# convert toml string to dictionary
# as_dict_again = ortoml.loads(as_toml)
# assert as_dict_again == as_dict, "Dictionaries are not matching"
| ycd/ortoml | 2 | [ABANDONED] Ultra fast, feature rich TOML library for Python written in Rust. | Rust | ycd | Yagiz Degirmenci | |
src/lib.rs | Rust | use std::{collections::HashMap, str::from_utf8};
use pyo3::wrap_pyfunction;
use pyo3::{prelude::*, types};
use toml;
#[pymodule]
fn ortoml(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(dumps, m)?).unwrap();
m.add_function(wrap_pyfunction!(loads, m)?).unwrap();
m.add_function(wrap_pyfunction!(to_json, m)?).unwrap();
m.add_function(wrap_pyfunction!(from_json, m)?).unwrap();
Ok(())
}
// Converts dictionary to YAML.
#[pyfunction]
fn dumps(dict: &pyo3::types::PyDict) -> PyResult<String> {
let gil = Python::acquire_gil();
let py = gil.python();
let orjson = PyModule::import(py, "orjson").unwrap();
let dict_string = orjson.call1("dumps", (dict,))?.str()?.to_str()?.as_bytes();
// This is used to convert python's b'' to => "".
// TODO(ycd): find something more safe(i think it is safe enough) but quite sure not the best practice though.
let ss = std::str::from_utf8(&dict_string[2..dict_string.iter().count() - 1])?;
let toml_str: toml::Value = match serde_json::from_str(&ss) {
Ok(v) => v,
Err(why) => panic!("an error occured: {}", why),
};
Ok(toml_str.to_string())
}
// Converts TOML object to dictionary.
#[pyfunction]
fn loads(s: &str) -> PyResult<pyo3::PyObject> {
let gil = Python::acquire_gil();
let py = gil.python();
let r = convert_to_json(toml::de::from_str(s).unwrap());
let v = serde_json::to_string(&r).unwrap();
let orjson = PyModule::import(py, "orjson")?;
let dict = orjson.call1("loads", (v,))?;
Ok(FromPyObject::extract(dict)?)
}
#[pyfunction]
fn to_json(s: &str) -> String {
let json = convert_to_json(toml::de::from_str(s).unwrap());
let v = serde_json::to_string(&json).unwrap();
v
}
#[pyfunction]
fn from_json(s: &str) -> String {
let v: toml::Value = serde_json::from_str(&s).unwrap();
let toml_text: String = v.to_string();
toml_text
}
// convert_to_json is used by to_json function
// to convert toml types to json.
fn convert_to_json(toml: toml::Value) -> serde_json::Value {
match toml {
toml::Value::String(s) => serde_json::Value::String(s),
toml::Value::Integer(i) => serde_json::Value::Number(i.into()),
toml::Value::Float(f) => {
let n = serde_json::Number::from_f64(f).expect("float infinite and nan not allowed");
serde_json::Value::Number(n)
}
toml::Value::Boolean(b) => serde_json::Value::Bool(b),
toml::Value::Array(arr) => {
serde_json::Value::Array(arr.into_iter().map(convert_to_json).collect())
}
toml::Value::Table(table) => serde_json::Value::Object(
table
.into_iter()
.map(|(k, v)| (k, convert_to_json(v)))
.collect(),
),
toml::Value::Datetime(dt) => serde_json::Value::String(dt.to_string()),
}
}
#[test]
fn test_loads() {
let v = crate::loads(
r#"
[dependencies]
a = "123"
b = 3
c = true
[naber]
abi = 123
"#,
);
}
#[test]
fn test_to_json() {
let v = crate::to_json(
r#"
[dependencies]
a = "123"
b = 3
c = true
[naber]
abi = 123
"#,
);
assert_eq!(
v,
"{\"dependencies\":{\"a\":\"123\",\"b\":3,\"c\":true},\"naber\":{\"abi\":123}}"
)
}
#[test]
fn test_from_json() {
let v = crate::from_json(
"{\"dependencies\":{\"a\":\"123\",\"b\":3,\"c\":true},\"naber\":{\"abi\":123}}",
);
assert_eq!(
"[dependencies]\na = \"123\"\nb = 3\nc = true\n\n[naber]\nabi = 123\n",
v
)
}
#[test]
fn test_dumps() {
use pyo3::prelude::*;
use pyo3::types::PyDict;
let gil = Python::acquire_gil();
let py = gil.python();
let dict = pyo3::types::PyDict::new(py);
dict.set_item("test", "value");
let new_dict = PyDict::new(py);
new_dict.set_item("test1", "valuefortest1");
dict.set_item("dict_inside_dict", new_dict);
dict.set_item("test1", "valueueueueue");
dict.set_item("test2", "another value");
dict.set_item("test3", "yet another value");
let v = crate::dumps(dict);
println!("{:#?}", dict)
}
| ycd/ortoml | 2 | [ABANDONED] Ultra fast, feature rich TOML library for Python written in Rust. | Rust | ycd | Yagiz Degirmenci | |
src/main/scala/Result.scala | Scala | package result
/** Provides Rust Result<T,E> like interface for handling function results.
*/
sealed trait Result[+T, +E] extends Any {
// Returns the contained ['Ok'] value, consuming the 'self' value
@throws(classOf[RuntimeException])
def unwrap: T = this match {
case Ok(v) => v
case Err(e) =>
throw new RuntimeException("called Result.unwrap() on an 'Err' value")
}
// Returns the contained ['Ok'] value or a provided default.
def unwrapOr[D >: T](default: D): D = this match {
case Err(_) => default
case Ok(v) => v
}
// Returns the contained [`Ok`] value or computes it from a closure.
def unwrapOrElse[U >: T, F >: E](f: F => U): U = this match {
case Err(e) => f(e)
case Ok(v) => v
}
// Returns `true` if the result is [`Ok`].
def isOk: Boolean = this match {
case Err(_) => false
case Ok(_) => true
}
// Returns `true` if the result is an [`Ok`] value containing the given value
def contains[U >: T](x: U): Boolean = this match {
case Err(_) => false
case Ok(v) => v == x
}
// Returns `true` if the result is an [`Err`] value containing the given value.
def containsErr[U >: E](x: U): Boolean = this match {
case Err(e) => x == e
case Ok(_) => false
}
// Returns `true` if the result is [`Err`].
def isErr: Boolean = this match {
case Err(_) => true
case Ok(_) => false
}
// Converts from `Result[T, E]` to [`Option[T]`].
def ok: Option[T] = this match {
case Err(_) => None
case Ok(v) => Some(v)
}
// Converts from Result[T, E]
def okOrElse[U >: T](e: U): U = this match {
case Err(_) => e
case Ok(v) => v
}
// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
def or[U >: T, M >: E](result: Result[U, M]): Result[U, M] =
this match {
case Err(_) => result
case _ => this
}
// Converts from `Result[T, E]` to [`Option[E]`].
def err: Option[E] = this match {
case Err(e) => Some(e)
case _ => None
}
// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
def and[U >: T, M >: E](res: Result[U, M]): Result[U, M] =
this match {
case Ok(_) => res
case Err(e) => Err(e)
}
// Maps a `Result[T, E]` to `Result[U, E]` by applying a function to a
// contained [`Ok`] value, leaving an [`Err`] value untouched.
def map[U](f: T => U): Result[U, E]
def flatMap[U, F >: E](f: T => Result[U, F]): Result[U, F]
}
case class Ok[T, E](v: T) extends AnyVal with Result[T, E] {
override def map[U](f: T => U): Result[U, E] = Ok(f(v))
override def flatMap[U, F >: E](f: T => Result[U, F]): Result[U, F] = f(v)
}
case class Err[T, E](e: E) extends AnyVal with Result[T, E] {
override def map[U](f: T => U): Result[U, E] = Err(e)
override def flatMap[U, F >: E](f: T => Result[U, F]): Result[U, F] = Err(e)
}
| ycd/result.scala | 1 | A Rust like Result[+T, +E] type for Scala | Scala | ycd | Yagiz Degirmenci | |
src/main.rs | Rust | #![feature(proc_macro_hygiene, decl_macro)]
#![feature(option_unwrap_none)]
#[macro_use]
extern crate rocket;
extern crate woothee;
use log::info;
use response::Redirect;
use rocket::{response, State};
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use utils::types::RequestHeaders;
use shortener::{
shortener::Analytics,
shortener::{AnalyticResults, Shortener},
url::Url,
};
mod shortener;
mod storage;
mod utils;
use std::{net::SocketAddr, sync::Mutex};
#[derive(Debug, Serialize)]
struct ShortenerResponse {
status_code: i16,
data: Option<Url>,
error: String,
}
#[derive(Deserialize, Debug)]
struct Shorten {
url: String,
}
struct SharedShortener {
url: Mutex<Shortener>,
}
#[derive(Debug, Responder)]
enum ResponseOrRedirect {
Response(Json<ShortenerResponse>),
// Use 301 Moved Permanently as status code
// to don't hurt website's SEO.
#[response(status = 301)]
Redirect(Redirect),
}
#[post("/api/shorten", data = "<shorten>")]
fn index<'a>(
shorten: Json<Shorten>,
shortener: State<'a, SharedShortener>,
) -> Json<ShortenerResponse> {
let shared_shortener: &SharedShortener = shortener.inner().clone();
let url = shared_shortener
.url
.lock()
.unwrap()
.shorten(&shorten.url)
.unwrap();
Json(ShortenerResponse {
status_code: 201,
data: Some(url),
error: String::new(),
})
}
#[get("/api/<id>")]
fn get_analytics_of_id<'a>(
id: String,
shortener: State<'a, SharedShortener>,
) -> Json<AnalyticResults> {
let shared_shortener: &SharedShortener = shortener.inner().clone();
let analytics = shared_shortener.url.lock().unwrap().get_analytics(id);
Json(analytics)
}
#[get("/<id>")]
fn redirect<'a>(
id: String,
shortener: State<'a, SharedShortener>,
headers: RequestHeaders,
client_ip: SocketAddr,
) -> ResponseOrRedirect {
// FIXME: this is for debugging purposes, should be deleted later.
info!("Got new request from {:?} to id: {}", client_ip, id);
let shared_shortener: &SharedShortener = shortener.inner();
let response: ResponseOrRedirect = match shared_shortener
.url
.lock()
.unwrap()
.get_original_url(id.clone())
{
Some(url) => ResponseOrRedirect::Redirect(Redirect::to(url)),
None => ResponseOrRedirect::Response(Json(ShortenerResponse {
status_code: 404,
data: None,
error: String::from("No URL found."),
})),
};
match response {
ResponseOrRedirect::Response(_) => {}
ResponseOrRedirect::Redirect(_) => {
match crossbeam::thread::scope(|scope| {
scope.spawn(move |_| {
shared_shortener
.url
.try_lock()
.unwrap()
.process_analytics(Analytics::new(
id.clone(),
headers.headers,
client_ip.to_string(),
));
});
}) {
Ok(_) => info!("successfully proccessed analytics"),
Err(e) => log::error!("error occured: {:#?}", e),
}
}
};
response
}
fn main() {
let shortener: Shortener = shortener::shortener::Shortener::new("shortener");
rocket::ignite()
.mount("/", routes![index, redirect, get_analytics_of_id])
.manage(SharedShortener {
url: Mutex::new(shortener),
})
.launch();
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/shortener/mod.rs | Rust | pub mod shortener;
pub mod url;
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/shortener/shortener.rs | Rust | use std::collections::HashMap;
use harsh::Harsh;
use mongodb::bson::doc;
use log::{error, info, warn};
use storage::storage::Storage;
use super::url::Url;
use crate::storage;
use mongodb::bson::{to_bson, Document};
use serde::Serialize;
pub struct Shortener {
pub id: u64,
pub generator: Harsh,
pub storage: Storage,
}
impl Shortener {
pub fn new(db_name: &str) -> Shortener {
let harsh = Harsh::default();
let storage = Storage::new(db_name);
// To create unique id every time we need an atomic
// counter to get or restore id from there
//
// It follows these steps
// 1- check mongodb for the key
// 1.2- if None found
// 1.3 - Create new object and return 0
// 2- return the current count.
let collection = storage.db.collection("counter");
let id: u64 = match collection.find_one(doc! {"name": "counter"}, None).unwrap() {
Some(document) => document.get_i64("count").unwrap() as u64,
None => match collection.insert_one(
doc! {
"name": "counter",
"count": 0 as u64,
},
None,
) {
Ok(res) => {
info!("successfully created count {:#?}", res);
0
}
Err(e) => {
error!("error occured, creating counter {:#?}", e);
panic!("counter creation failed, exiting");
}
},
};
Shortener {
id: id,
generator: harsh,
storage: storage,
}
}
pub fn next_id(&mut self) -> String {
let hashed = self.generator.encode(&[self.id]);
let _ = match self.increment_counter() {
Ok(_) => self.id += 1,
Err(e) => error!("error occured, calling next_id : {}", e),
};
hashed
}
pub fn get_original_url(&self, id: String) -> Option<String> {
let collection = self.storage.db.collection("shortener");
let original_url: Option<String> =
match collection.find_one(doc! {"id": &id}, None).unwrap() {
Some(document) => Some(document.get_str("long_url").unwrap().to_string()),
None => {
info!("no document found for id={}", &id);
None
}
};
original_url
}
fn increment_counter(&self) -> Result<(), mongodb::error::Error> {
let collection = self.storage.db.collection("counter");
match collection.update_one(doc! {"name": "counter"}, doc! {"$inc": {"count": 1}}, None) {
Ok(result) => info!("successfully incremented counter: {:#?}", result),
Err(e) => error!("error occured, incrementing atomic counter: {}", e),
};
Ok(())
}
pub fn shorten(&mut self, url: &str) -> Result<Url, mongodb::error::Error> {
let collection = self.storage.db.collection("shortener");
// Create new URL record from the input URL.
let url_record = Url::new_record(self.next_id(), String::from(url));
match collection.insert_one(url_record.to_document(), None) {
Ok(result) => info!("successfully shortened url: {:#?}", result),
Err(e) => error!("error occured, inserting shortened url: {}", e),
}
Ok(url_record)
}
}
#[derive(Debug, Serialize)]
pub struct Analytics {
pub id: String,
pub headers: HashMap<String, String>,
pub ip: String,
time: chrono::DateTime<chrono::Utc>,
}
impl Analytics {
pub fn new(id: String, headers: HashMap<String, String>, ip: String) -> Analytics {
Analytics {
id: id,
headers: headers,
ip: ip,
time: chrono::Utc::now(),
}
}
pub fn to_document(&self) -> Document {
to_bson(&self).unwrap().as_document().unwrap().clone()
}
}
impl Shortener {
pub fn process_analytics(&self, analytics: Analytics) {
let analytics_db = self.storage.db.collection("analytics");
match analytics_db.insert_one(analytics.to_document(), None) {
Ok(res) => info!("result from analytics process {:#?}", res),
Err(e) => error!("error occured, analytics process {:#?}", e),
};
println!("{:#?}", analytics.to_document());
}
}
#[derive(Debug, Serialize)]
pub struct AnalyticResults {
pub count: u64,
pub client_os: HashMap<String, u32>,
pub devices: HashMap<String, u32>,
}
impl AnalyticResults {
fn new() -> AnalyticResults {
AnalyticResults {
count: 0 as u64,
client_os: HashMap::new(),
devices: HashMap::new(),
}
}
}
impl Shortener {
pub fn get_analytics(&self, id: String) -> AnalyticResults {
let analytics_db = self.storage.db.collection("analytics");
let parser = woothee::parser::Parser::new();
let mut analytics_results: AnalyticResults = AnalyticResults::new();
match analytics_db.find(doc! {"id": &id}, None) {
Ok(result) => {
let mut client_os: HashMap<String, u32> = HashMap::new();
let mut devices: HashMap<String, u32> = HashMap::new();
let mut count: u64 = 0;
for res in result {
match res {
Ok(document) => {
let user_agent = parser.parse(
document
.get_document("headers")
.unwrap()
.get_str("User-Agent")
.unwrap(),
);
count += 1;
match user_agent {
Some(ua) => {
let _ = match devices.get_mut(&ua.category.to_string()) {
Some(v) => *v += 1,
None => {
devices.insert(ua.category.to_string(), 1).unwrap_none()
}
};
let _ = match client_os.get_mut(&ua.os.to_string()) {
Some(v) => *v += 1,
None => {
client_os.insert(ua.os.to_string(), 1).unwrap_none()
}
};
}
None => warn!("no user agent found"),
}
}
Err(_) => {}
}
}
analytics_results = AnalyticResults {
devices: devices,
count: count,
client_os: client_os,
}
}
Err(e) => error!("error occured while getting analytics {:#?}", e),
}
analytics_results
}
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/shortener/url.rs | Rust | use mongodb::bson::{doc, to_bson, Document};
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct Url {
pub archived: bool,
pub created_at: chrono::DateTime<chrono::Utc>,
pub id: String,
pub link: String,
pub long_url: String,
}
impl Url {
pub fn new_record(id: String, long_url: String) -> Url {
Url {
created_at: chrono::Utc::now(),
id: String::from(&id),
archived: false,
long_url: long_url,
link: format!("https://sho.rs/{}", String::from(&id)),
}
}
pub fn to_document(&self) -> Document {
to_bson(&self).unwrap().as_document().unwrap().clone()
}
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/storage/config.rs | Rust | use dotenv;
#[derive(Debug)]
pub struct Config {
pub server_ip: String,
pub dbname: String,
pub username: String,
pub password: String,
}
impl Config {
// Create a new Config for your MongoDB,
// Get's server_ip, dbname, username, password
// from the ".env" file
pub fn new() -> Result<Config, Box<dyn std::error::Error>> {
// Get values from .env file if default
match dotenv::dotenv().ok() {
Some(p) => Some(p),
None => dotenv::from_filename(".env").ok(),
};
let server_ip = dotenv::var("MONGO_SERVER_IP")?;
let dbname = dotenv::var("MONGO_DBNAME")?;
let username = dotenv::var("MONGO_USERNAME")?;
let password = dotenv::var("MONGO_PASSWORD")?;
Ok(Config {
server_ip: server_ip,
dbname: dbname,
username: username,
password: password,
})
}
pub fn uri(&self) -> String {
format!(
"mongodb+srv://{}:{}@{}/{}?retryWrites=true&w=majority",
self.username, self.password, self.server_ip, self.dbname
)
}
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/storage/mod.rs | Rust | pub mod config;
pub mod storage;
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/storage/storage.rs | Rust | use super::config;
use mongodb::sync::{Client, Database};
// Storage represents mongodb client and the config for it.
pub struct Storage {
pub config: config::Config,
pub client: mongodb::sync::Client,
pub db: Database,
}
impl Storage {
pub fn new(db_name: &str) -> Storage {
let config = config::Config::new().unwrap();
let config_uri = config.uri();
let client = Client::with_uri_str(config_uri.as_str()).unwrap();
let db = client.database(db_name);
Storage {
config: config,
client: client,
db: db,
}
}
pub fn database<'a>(&self, db_name: &'a str) -> Result<Database, Box<dyn std::error::Error>> {
Ok(self.client.database(db_name))
}
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/utils/mod.rs | Rust | pub mod types;
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
src/utils/types.rs | Rust | use rocket::{
request::{FromRequest, Outcome},
Request,
};
use std::{collections::HashMap, convert::Infallible};
// Get request headers for any
// incoming HTTP requests.
#[derive(Debug)]
pub struct RequestHeaders {
pub headers: HashMap<String, String>,
}
impl<'a, 'r> FromRequest<'a, 'r> for RequestHeaders {
type Error = Infallible;
fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
let headers: HashMap<String, String> = request
.headers()
.iter()
.map(|h| (h.name().to_string(), h.value().to_string()))
.collect();
rocket::Outcome::Success(Self { headers: headers })
}
}
#[derive(Debug)]
pub struct RequestSocketAddr {
pub socket_addr: String,
}
impl<'a, 'r> FromRequest<'a, 'r> for RequestSocketAddr {
type Error = Infallible;
fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
let socket_addr: String = request.remote().unwrap().to_string();
rocket::Outcome::Success(Self {
socket_addr: socket_addr,
})
}
}
| ycd/sho.rs | 1 | An unreasonably high-performance, experimental URL shortener with strong-consistency model built on top of MongoDB | Rust | ycd | Yagiz Degirmenci | |
autoppt/__init__.py | Python | """
AutoPPT - AI-Powered Presentation Generator
"""
from .generator import Generator
from .config import Config
from .llm_provider import get_provider, BaseLLMProvider
from .researcher import Researcher
from .ppt_renderer import PPTRenderer
from .exceptions import AutoPPTError
__version__ = "0.4.0"
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/app.py | Python | #!/usr/bin/env python3
"""
AutoPPT Web Interface
A Streamlit-based web UI for generating AI-powered presentations.
Run with: streamlit run app.py
"""
import streamlit as st
import os
import tempfile
import time
from datetime import datetime
# Page configuration
st.set_page_config(
page_title="AutoPPT - AI Presentation Generator",
page_icon="🚀",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for styling
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
color: #1E88E5;
text-align: center;
margin-bottom: 1rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
text-align: center;
margin-bottom: 2rem;
}
.stButton>button {
width: 100%;
height: 3rem;
font-size: 1.1rem;
font-weight: bold;
}
.success-box {
padding: 1rem;
border-radius: 0.5rem;
background-color: #E8F5E9;
border: 1px solid #4CAF50;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown('<div class="main-header">🚀 AutoPPT</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-header">Generate Professional Presentations with AI</div>', unsafe_allow_html=True)
# Sidebar configuration
with st.sidebar:
st.header("⚙️ Configuration")
# Provider selection
provider = st.selectbox(
"🤖 AI Provider",
options=["mock", "google", "openai", "anthropic"],
index=0,
help="Select the AI provider. Use 'mock' for testing without API keys."
)
# Model selection (only for non-mock providers)
model = None
if provider != "mock":
model_options = {
"openai": ["gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"],
"google": ["gemini-2.0-flash", "gemini-1.5-pro"],
"anthropic": ["claude-3-5-sonnet-20241022", "claude-3-opus-20240229"]
}
model = st.selectbox(
"🧠 Model",
options=model_options.get(provider, []),
help="Select the specific model to use."
)
# Style selection
style = st.selectbox(
"🎨 Visual Theme",
options=[
"minimalist", "technology", "nature", "creative",
"corporate", "academic", "startup", "dark"
],
index=0,
help="Choose the visual theme for your presentation."
)
# Slides count
slides_count = st.slider(
"📊 Number of Slides",
min_value=3,
max_value=20,
value=6,
help="Target number of content slides."
)
# Language
language = st.text_input(
"🌐 Language",
value="English",
help="Output language for the presentation content."
)
st.divider()
# API Key status
st.header("🔑 API Keys")
from dotenv import load_dotenv
load_dotenv()
openai_key = os.getenv("OPENAI_API_KEY")
google_key = os.getenv("GOOGLE_API_KEY")
anthropic_key = os.getenv("ANTHROPIC_API_KEY")
st.write("OpenAI:", "✅ Set" if openai_key else "❌ Not set")
st.write("Google:", "✅ Set" if google_key else "❌ Not set")
st.write("Anthropic:", "✅ Set" if anthropic_key else "❌ Not set")
if provider != "mock" and not any([openai_key, google_key, anthropic_key]):
st.warning("⚠️ No API keys found. Please set them in .env file or use 'mock' provider.")
# Main content area
col1, col2 = st.columns([2, 1])
with col1:
st.header("📝 Presentation Topic")
topic = st.text_area(
"Enter your presentation topic",
placeholder="e.g., The Future of Artificial Intelligence\n人工智能的发展历史\nClimate Change and Renewable Energy",
height=100,
label_visibility="collapsed"
)
with col2:
st.header("📋 Preview")
st.info(f"""
**Topic:** {topic or 'Not specified'}
**Provider:** {provider}
**Style:** {style}
**Slides:** {slides_count}
**Language:** {language}
""")
st.divider()
# Generate button
generate_button = st.button("🚀 Generate Presentation", type="primary", use_container_width=True)
if generate_button:
if not topic:
st.error("❌ Please enter a presentation topic.")
else:
# Check API key for non-mock providers
if provider != "mock":
key_map = {
"openai": openai_key,
"google": google_key,
"anthropic": anthropic_key
}
if not key_map.get(provider):
st.error(f"❌ API key for {provider} is not set. Please configure it in .env file.")
st.stop()
# Generate presentation
with st.spinner("🔄 Generating your presentation... This may take a few minutes."):
try:
from .generator import Generator
# Create output directory
output_dir = tempfile.mkdtemp()
safe_topic = "".join(c for c in topic if c.isalnum() or c in (' ', '-', '_'))[:50]
output_file = os.path.join(output_dir, f"{safe_topic.replace(' ', '_')}.pptx")
# Progress tracking
progress_bar = st.progress(0, text="Initializing generator...")
# Initialize generator
gen = Generator(provider_name=provider, model=model)
progress_bar.progress(10, text="Generating outline...")
# Generate presentation
result = gen.generate(
topic=topic,
style=style,
output_file=output_file,
slides_count=slides_count,
language=language
)
progress_bar.progress(100, text="✅ Complete!")
time.sleep(0.5)
progress_bar.empty()
# Success message
st.success("🎉 Presentation generated successfully!")
# File info and download
file_size = os.path.getsize(result) / 1024 # KB
st.info(f"📁 File size: {file_size:.1f} KB")
# Download button
with open(result, "rb") as f:
st.download_button(
label="📥 Download Presentation",
data=f.read(),
file_name=f"{safe_topic.replace(' ', '_')}.pptx",
mime="application/vnd.openxmlformats-officedocument.presentationml.presentation",
use_container_width=True
)
except Exception as e:
st.error(f"❌ Error generating presentation: {str(e)}")
st.exception(e)
# Footer
st.divider()
st.markdown("""
<div style="text-align: center; color: #888; font-size: 0.9rem;">
<p>AutoPPT v0.3 | <a href="https://github.com/yeasy/autoppt">GitHub</a> | Apache 2.0 License</p>
</div>
""", unsafe_allow_html=True)
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/config.py | Python | import os
import logging
from dotenv import load_dotenv
load_dotenv()
# Configure logging for the entire application
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
class Config:
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
# Defaults - synchronized with actual provider implementations
DEFAULT_OPENAI_MODEL = "gpt-4o"
DEFAULT_GOOGLE_MODEL = "gemini-2.0-flash"
DEFAULT_ANTHROPIC_MODEL = "claude-3-5-sonnet-20241022"
OUTPUT_DIR = "output"
# Performance settings
API_RETRY_ATTEMPTS = 3
API_RETRY_DELAY_SECONDS = 60
IMAGE_DOWNLOAD_TIMEOUT = 30
@staticmethod
def validate() -> bool:
"""Validate that at least one API key is configured."""
if not Config.OPENAI_API_KEY and not Config.ANTHROPIC_API_KEY and not Config.GOOGLE_API_KEY:
logger.warning("No API keys found in .env file. Use --provider mock for testing.")
return False
return True
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/data_types.py | Python | from pydantic import BaseModel, Field
from typing import List, Optional
from enum import Enum
class ChartType(str, Enum):
"""Supported chart types for PPT generation."""
BAR = "bar"
PIE = "pie"
LINE = "line"
COLUMN = "column"
class ChartData(BaseModel):
"""Data structure for chart generation."""
chart_type: ChartType = Field(description="Type of chart: bar, pie, line, or column")
title: str = Field(description="Chart title")
categories: List[str] = Field(description="Category labels for the X-axis or pie slices")
values: List[float] = Field(description="Numeric values corresponding to each category")
series_name: str = Field(default="Series 1", description="Name of the data series")
class SlideType(str, Enum):
"""Types of slides available for generation."""
CONTENT = "content" # Standard bullet points
CHART = "chart" # Data visualization
STATISTICS = "statistics" # Key numbers highlight
IMAGE = "image" # Fullscreen image
class StatisticData(BaseModel):
"""Data for a single statistic highlight."""
value: str = Field(description="The number/value to highlight (e.g., '85%', '$4B')")
label: str = Field(description="Short description label")
class SlideConfig(BaseModel):
"""Configuration for a single slide's content."""
title: str = Field(description="The main title of the slide")
slide_type: SlideType = Field(default=SlideType.CONTENT, description="Type of slide layout to use")
bullets: List[str] = Field(description="List of 5-8 detailed bullet points (for content slides)")
image_query: Optional[str] = Field(None, description="A search query to find an image for this slide")
speaker_notes: Optional[str] = Field(None, description="Speaker notes for this slide")
citations: List[str] = Field(default_factory=list, description="List of source URLs used for this slide")
chart_data: Optional[ChartData] = Field(None, description="Data for chart slides")
statistics: Optional[List[StatisticData]] = Field(None, description="List of 3-4 key stats for statistics slides")
class PresentationSection(BaseModel):
"""A section/chapter of the presentation containing multiple slides."""
title: str = Field(description="Title of the section or chapter")
slides: List[str] = Field(description="List of slide topics within this section")
class PresentationOutline(BaseModel):
"""Complete outline of a presentation with hierarchical sections."""
title: str = Field(description="Main title of the presentation")
sections: List[PresentationSection] = Field(description="List of hierarchical sections/chapters")
class UserPresentation(BaseModel):
"""User-defined presentation structure."""
title: str
sections: List[PresentationSection]
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/exceptions.py | Python | """
Custom exceptions for AutoPPT.
These exceptions provide user-friendly error messages and enable
structured error handling throughout the application.
"""
class AutoPPTError(Exception):
"""Base exception for all AutoPPT errors."""
pass
class APIKeyError(AutoPPTError):
"""Raised when an API key is missing or invalid."""
def __init__(self, provider: str, message: str = None):
self.provider = provider
self.message = message or f"API key for '{provider}' is missing or invalid. Please check your .env file."
super().__init__(self.message)
class RateLimitError(AutoPPTError):
"""Raised when API rate limits are exceeded."""
def __init__(self, provider: str, retry_after: int = None):
self.provider = provider
self.retry_after = retry_after
if retry_after:
self.message = f"Rate limit exceeded for '{provider}'. Please retry after {retry_after} seconds."
else:
self.message = f"Rate limit exceeded for '{provider}'. Please wait and try again later."
super().__init__(self.message)
class ResearchError(AutoPPTError):
"""Raised when research/web search operations fail."""
def __init__(self, query: str, reason: str = None):
self.query = query
self.reason = reason or "Unknown error"
self.message = f"Failed to research '{query}': {self.reason}"
super().__init__(self.message)
class RenderError(AutoPPTError):
"""Raised when PPT rendering operations fail."""
def __init__(self, operation: str, reason: str = None):
self.operation = operation
self.reason = reason or "Unknown error"
self.message = f"Failed to render '{operation}': {self.reason}"
super().__init__(self.message)
class ModelNotFoundError(AutoPPTError):
"""Raised when the specified LLM model is not available."""
def __init__(self, model: str, provider: str):
self.model = model
self.provider = provider
self.message = f"Model '{model}' is not available for provider '{provider}'."
super().__init__(self.message)
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/generator.py | Python | import os
import shutil
import logging
import time
from typing import Optional
from tqdm import tqdm
from .llm_provider import get_provider, BaseLLMProvider, MockProvider
from .researcher import Researcher
from .ppt_renderer import PPTRenderer
from .data_types import PresentationOutline, SlideConfig, UserPresentation, SlideType
from .exceptions import AutoPPTError, RateLimitError, ResearchError, RenderError
from .config import Config
logger = logging.getLogger(__name__)
class Generator:
"""Main presentation generator class."""
def __init__(self, provider_name: str = "openai", api_key: str = None, model: str = None):
self.llm = get_provider(provider_name, model=model)
self.researcher = Researcher()
self.renderer = PPTRenderer()
self.provider_name = provider_name
def generate(
self,
topic: str,
style: str = "minimalist",
output_file: str = "output.pptx",
slides_count: int = 10,
language: str = "English"
) -> str:
"""
Generate a complete presentation on the given topic.
Args:
topic: The main topic of the presentation
style: Visual theme (minimalist, technology, nature, creative, corporate, academic, startup, dark)
output_file: Output file path
slides_count: Target number of slides
language: Output language
Returns:
Path to the generated presentation file
"""
logger.info(f"Starting generation for topic: {topic}")
logger.info(f"Style: {style}, Slides: {slides_count}, Language: {language}")
# Ensure fresh renderer for each call
self.renderer = PPTRenderer()
# 0. Apply Style
self.renderer.apply_style(style)
# 1. Generate Outline
logger.info("Generating presentation outline...")
outline = self._create_outline(topic, slides_count, language)
logger.info(f"Outline created: {len(outline.sections)} sections")
# Count total slides for progress bar
total_slides = sum(len(section.slides) for section in outline.sections)
# 2. Research & Create Content for each section and slide
all_citations = []
# Ensure temp directory for images
temp_dir = "temp_images"
os.makedirs(temp_dir, exist_ok=True)
self.renderer.add_title_slide(outline.title, f"Topic: {topic}")
# Progress bar for sections and slides
with tqdm(total=total_slides, desc="Generating slides", unit="slide") as pbar:
for s_idx, section in enumerate(outline.sections):
logger.info(f"Processing Section {s_idx+1}/{len(outline.sections)}: {section.title}")
self.renderer.add_section_header(section.title)
for i, slide_title in enumerate(section.slides):
pbar.set_description(f"Slide: {slide_title[:30]}...")
# Rate limiting safety for paid APIs (skip for mock)
if not isinstance(self.llm, MockProvider):
delay = Config.API_RETRY_DELAY_SECONDS
logger.debug(f"Rate limit delay: {delay}s")
time.sleep(delay)
try:
# Research
search_query = f"{slide_title} {section.title} {topic}"
context = self.researcher.gather_context([search_query])
# Draft Content
slide_config = self._create_slide_content(slide_title, context, style, language, topic)
# Fetch Image
image_path = None
if slide_config.image_query:
image_results = self.researcher.search_images(slide_config.image_query, max_results=1)
if image_results:
img_url = image_results[0]['image']
local_path = os.path.join(temp_dir, f"section_{s_idx}_slide_{i}.jpg")
if self.researcher.download_image(img_url, local_path):
image_path = local_path
# Render Slide based on Type
if slide_config.slide_type == SlideType.STATISTICS and slide_config.statistics:
# Convert pydantic stats to list of dicts for renderer
stats_dicts = [{"value": s.value, "label": s.label} for s in slide_config.statistics]
self.renderer.add_statistics_slide(
slide_config.title,
stats_dicts,
slide_config.speaker_notes
)
elif slide_config.slide_type == SlideType.IMAGE and image_path:
self.renderer.add_fullscreen_image_slide(
image_path,
caption=slide_config.bullets[0] if slide_config.bullets else "",
overlay_title=slide_config.title
)
elif slide_config.chart_data and slide_config.slide_type == SlideType.CHART:
self.renderer.add_chart_slide(
slide_config.title,
slide_config.chart_data,
slide_config.speaker_notes
)
else:
# Default to content slide
self.renderer.add_content_slide(
slide_config.title,
slide_config.bullets,
slide_config.speaker_notes,
image_path=image_path
)
all_citations.extend(slide_config.citations)
except Exception as e:
logger.error(f"Error generating slide '{slide_title}': {e}")
# Add a placeholder slide instead of failing
self.renderer.add_content_slide(
slide_title,
[f"Content generation failed: {str(e)[:50]}"],
"Please regenerate this slide."
)
pbar.update(1)
# 3. Finalize PPT
logger.info("Finalizing presentation...")
# Add References
unique_citations = list(set(all_citations))
if unique_citations:
self.renderer.add_citations_slide(unique_citations)
self.renderer.save(output_file)
# Cleanup temp images
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
logger.info(f"✅ Done! Saved to {output_file}")
return output_file
def _create_outline(self, topic: str, slides_count: int, language: str) -> PresentationOutline:
"""Generate a hierarchical outline for the presentation."""
prompt = f"""
Create a professional hierarchical outline for a {slides_count}-slide presentation on: '{topic}'.
Divide the presentation into 3-5 logical sections (chapters).
Each section should contain a list of relevant slide topics.
Ensure the structure flows logically from introduction to conclusion.
Language: {language}.
"""
return self.llm.generate_structure(prompt, PresentationOutline)
def _create_slide_content(
self,
slide_title: str,
context: str,
style: str,
language: str,
topic: str
) -> SlideConfig:
"""Generate content for a single slide using research context."""
system_prompt = f"""You are a top-tier research analyst and professional presentation architect.
Style: {style}.
Your objective is to transform raw data into high-density, substantive insights (Dry Goods / 干货).
Output Language: {language}."""
prompt = f"""
Objective: Create COMPREHENSIVE, authoritative content for a slide titled: '{slide_title}' as part of a presentation on '{topic}'.
Research Context (from Web/Wikipedia):
{context[:12000]}
===== MANDATORY CONTENT STANDARDS =====
0. **SLIDE TYPE SELECTION**:
- **'statistics'**: If the research contains 3+ strong numerical data points (market size, growth rates, survey results). FILL 'statistics' field.
- **'image'**: If the slide is about a visual concept, product design, or emotional impact.
- **'content'**: Default for informational text.
- **'chart'**: only if you have clear categorical data for comparison.
1. **CONTENT DENSITY (CRITICAL)**:
- Generate 5-8 SUBSTANTIVE bullet points (not 3-5)
- Each bullet should be 1-2 sentences of REAL information
- Use sub-bullets (indented with " •") to add details, examples, or statistics
- Total content should fill at least 60% of the slide area
2. **DATA-RICH REQUIREMENTS**:
- Include AT LEAST 3 specific numbers/statistics/dates
- Reference real companies, researchers, or institutions by name
- Cite specific percentages, growth rates, or measurements
- Example GOOD: "Tesla's Model 3 achieved 82% battery efficiency in 2023 tests (NREL)"
- Example BAD: "Electric vehicles are becoming more efficient"
3. **STRUCTURAL DEPTH**:
- First bullet: Key definition or core concept
- Middle bullets: Specific examples, data points, case studies
- Final bullet: Current trends, future outlook, or key implications
- Use sub-bullets liberally for complex points
4. **SPEAKER NOTES**:
- Write 5-7 professional sentences (not 3-4)
- Include additional context, anecdotes, or Q&A preparation points
- Mention any caveats or nuances not on the slide
5. **IMAGE QUERY**:
- Be HIGHLY specific and artistic
- Include style keywords: "4K", "cinematic", "professional photography", "infographic style"
- Example: "4K cinematic aerial view of solar panel farm at golden hour with dramatic shadows"
6. **CITATIONS**: List ALL source URLs from research context used.
7. **LANGUAGE**: {language}
"""
return self.llm.generate_structure(prompt, SlideConfig, system_prompt=system_prompt)
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/llm_provider.py | Python | import os
import logging
import time
from abc import ABC, abstractmethod
from typing import List, Type, TypeVar
from pydantic import BaseModel
from openai import OpenAI
from google import genai
from google.genai import types
from .exceptions import APIKeyError, RateLimitError
from .config import Config
logger = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseModel)
class BaseLLMProvider(ABC):
@abstractmethod
def generate_text(self, prompt: str, system_prompt: str = "") -> str:
"""Generate a simple text response."""
pass
@abstractmethod
def generate_structure(self, prompt: str, schema: Type[T], system_prompt: str = "") -> T:
"""Generate a structured Pydantic object."""
pass
class OpenAIProvider(BaseLLMProvider):
def __init__(self, api_key: str = None, model: str = "gpt-5.2"):
self.client = OpenAI(api_key=api_key or os.getenv("OPENAI_API_KEY"))
self.model = model
def generate_text(self, prompt: str, system_prompt: str = "") -> str:
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
temperature=0.7
)
return response.choices[0].message.content
def generate_structure(self, prompt: str, schema: Type[T], system_prompt: str = "") -> T:
completion = self.client.beta.chat.completions.parse(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
response_format=schema,
)
return completion.choices[0].message.parsed
class GoogleProvider(BaseLLMProvider):
def __init__(self, api_key: str = None, model: str = "gemini-2.0-flash"):
api_key = api_key or os.getenv("GOOGLE_API_KEY")
self.client = genai.Client(api_key=api_key)
self.model_id = model
def generate_text(self, prompt: str, system_prompt: str = "") -> str:
import time
for attempt in range(3):
try:
response = self.client.models.generate_content(
model=self.model_id,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.7
),
contents=prompt
)
return response.text
except Exception as e:
if "429" in str(e) and attempt < 2:
print(f"Rate limit hit, retrying in 60s... (Attempt {attempt+1}/3)")
time.sleep(60)
else:
raise e
def generate_structure(self, prompt: str, schema: Type[T], system_prompt: str = "") -> T:
import time
for attempt in range(3):
try:
response = self.client.models.generate_content(
model=self.model_id,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=schema,
temperature=0.2
),
contents=prompt
)
return response.parsed
except Exception as e:
if "429" in str(e) and attempt < 2:
logger.warning(f"Rate limit hit, retrying in {Config.API_RETRY_DELAY_SECONDS}s... (Attempt {attempt+1}/{Config.API_RETRY_ATTEMPTS})")
time.sleep(Config.API_RETRY_DELAY_SECONDS)
else:
raise RateLimitError("google", Config.API_RETRY_DELAY_SECONDS)
class AnthropicProvider(BaseLLMProvider):
"""Provider for Anthropic Claude models."""
def __init__(self, api_key: str = None, model: str = None):
try:
import anthropic
except ImportError:
raise ImportError("Please install anthropic: pip install anthropic")
api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not api_key:
raise APIKeyError("anthropic")
self.client = anthropic.Anthropic(api_key=api_key)
self.model = model or Config.DEFAULT_ANTHROPIC_MODEL
def generate_text(self, prompt: str, system_prompt: str = "") -> str:
for attempt in range(Config.API_RETRY_ATTEMPTS):
try:
message = self.client.messages.create(
model=self.model,
max_tokens=4096,
system=system_prompt,
messages=[
{"role": "user", "content": prompt}
]
)
return message.content[0].text
except Exception as e:
if "rate" in str(e).lower() and attempt < Config.API_RETRY_ATTEMPTS - 1:
logger.warning(f"Rate limit hit, retrying in {Config.API_RETRY_DELAY_SECONDS}s... (Attempt {attempt+1}/{Config.API_RETRY_ATTEMPTS})")
time.sleep(Config.API_RETRY_DELAY_SECONDS)
else:
raise e
def generate_structure(self, prompt: str, schema: Type[T], system_prompt: str = "") -> T:
import json
# Anthropic doesn't have native structured output, so we prompt for JSON
schema_description = schema.model_json_schema()
enhanced_prompt = f"""
{prompt}
You MUST respond with valid JSON that matches this schema:
{json.dumps(schema_description, indent=2)}
Respond ONLY with the JSON object, no additional text.
"""
for attempt in range(Config.API_RETRY_ATTEMPTS):
try:
message = self.client.messages.create(
model=self.model,
max_tokens=4096,
system=system_prompt,
messages=[
{"role": "user", "content": enhanced_prompt}
]
)
response_text = message.content[0].text
# Parse and validate against schema
data = json.loads(response_text)
return schema.model_validate(data)
except Exception as e:
if "rate" in str(e).lower() and attempt < Config.API_RETRY_ATTEMPTS - 1:
logger.warning(f"Rate limit hit, retrying in {Config.API_RETRY_DELAY_SECONDS}s... (Attempt {attempt+1}/{Config.API_RETRY_ATTEMPTS})")
time.sleep(Config.API_RETRY_DELAY_SECONDS)
else:
raise e
class MockProvider(BaseLLMProvider):
"""Mock provider for testing without API keys."""
def generate_text(self, prompt: str, system_prompt: str = "") -> str:
return f"This is a high-quality researched content for your presentation. It covers the key aspects of the requested topic with depth and clarity, ensuring a professional delivery. Citation: [Source 2025]"
def generate_structure(self, prompt: str, schema: Type[T], system_prompt: str = "") -> T:
from .data_types import PresentationSection
# Try to extract topic for better mock data
topic = "Current Topic"
if "topic:" in prompt.lower():
topic = prompt.lower().split("topic:")[1].split("\n")[0].strip()
elif "about" in prompt.lower():
topic = prompt.lower().split("about")[1].split("\n")[0].strip()
dummy_data = {}
for field_name, field in schema.model_fields.items():
if field.annotation == str:
if "title" in field_name.lower():
dummy_data[field_name] = f"Overview of {topic}"
elif "image_query" in field_name.lower():
dummy_data[field_name] = f"professional artistic image of {topic}"
else:
dummy_data[field_name] = f"Comprehensive analysis and professional insight into {topic}."
elif field.annotation == List[str]:
dummy_data[field_name] = [
f"Key innovation and strategic importance of {topic}",
f"Global impact and future trends in {topic}",
f"Practical applications and case studies of {topic}"
]
elif "slide_type" in field_name:
from .data_types import SlideType
dummy_data[field_name] = SlideType.CONTENT
elif field.annotation == List[PresentationSection]:
dummy_data[field_name] = [
PresentationSection(title=f"Fundamentals of {topic}", slides=[f"Introduction to {topic}", f"Core Concepts of {topic}"]),
PresentationSection(title=f"Advanced Applications: {topic}", slides=[f"Case Study: {topic}", f"Economic Impact"]),
PresentationSection(title=f"The Future of {topic}", slides=[f"Predictions for {topic}", f"Strategic Roadmap"])
]
else:
dummy_data[field_name] = None
return schema.model_validate(dummy_data)
def get_provider(provider_name: str, model: str = None) -> BaseLLMProvider:
"""Factory function to get the appropriate LLM provider."""
provider_name = provider_name.lower()
if provider_name == "openai":
return OpenAIProvider(model=model) if model else OpenAIProvider()
elif provider_name == "google":
return GoogleProvider(model=model) if model else GoogleProvider()
elif provider_name == "anthropic":
return AnthropicProvider(model=model) if model else AnthropicProvider()
elif provider_name == "mock":
return MockProvider()
else:
raise ValueError(f"Unknown provider: {provider_name}. Supported: openai, google, anthropic, mock")
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/main.py | Python | #!/usr/bin/env python3
"""
AutoPPT - AI-Powered Presentation Generator
Generate professional PowerPoint presentations using AI and real-time research.
"""
import argparse
import sys
import os
import logging
from .config import Config
from .exceptions import APIKeyError, RateLimitError
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%H:%M:%S'
)
logger = logging.getLogger(__name__)
SUPPORTED_THEMES = [
"minimalist", "technology", "nature", "creative",
"corporate", "academic", "startup", "dark"
]
SUPPORTED_PROVIDERS = ["openai", "google", "anthropic", "mock"]
def main():
parser = argparse.ArgumentParser(
description="AutoPPT - Generate professional presentations using AI",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python main.py --topic "The Future of AI" --style technology
python main.py --topic "Healthy Living" --provider google --slides 8
python main.py --topic "Test Topic" --provider mock # No API key needed
"""
)
parser.add_argument("--topic", required=True, help="Topic for the presentation")
parser.add_argument(
"--style",
default="minimalist",
choices=SUPPORTED_THEMES,
help=f"Visual theme: {', '.join(SUPPORTED_THEMES)}"
)
parser.add_argument(
"--provider",
default="openai",
choices=SUPPORTED_PROVIDERS,
help=f"LLM Provider: {', '.join(SUPPORTED_PROVIDERS)}"
)
parser.add_argument("--slides", type=int, default=10, help="Number of slides (default: 10)")
parser.add_argument("--language", default="English", help="Output language (default: English)")
parser.add_argument("--model", help="Specific LLM model name to use")
parser.add_argument("--output", help="Output file path (default: output/<topic>.pptx)")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose logging")
args = parser.parse_args()
# Configure verbose logging
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
# Validate configuration
if args.provider != "mock":
Config.validate()
# Determine output path
if args.output:
output_filename = args.output
else:
output_filename = f"output/{args.topic.replace(' ', '_')}.pptx"
# Print configuration
logger.info("=" * 50)
logger.info("AutoPPT - AI Presentation Generator")
logger.info("=" * 50)
logger.info(f"Topic: {args.topic}")
logger.info(f"Style: {args.style}")
logger.info(f"Provider: {args.provider}")
logger.info(f"Slides: {args.slides}")
logger.info(f"Language: {args.language}")
if args.model:
logger.info(f"Model: {args.model}")
logger.info(f"Output: {output_filename}")
logger.info("=" * 50)
try:
from .generator import Generator
# Ensure output directory exists
os.makedirs(os.path.dirname(output_filename) or "output", exist_ok=True)
gen = Generator(provider_name=args.provider, model=args.model)
result = gen.generate(
args.topic,
style=args.style,
output_file=output_filename,
slides_count=args.slides,
language=args.language
)
logger.info("=" * 50)
logger.info(f"✅ SUCCESS! Presentation saved to: {result}")
logger.info("=" * 50)
except APIKeyError as e:
logger.error(f"❌ API Key Error: {e.message}")
logger.info("💡 Tip: Set up your API key in the .env file, or use --provider mock for testing.")
sys.exit(1)
except RateLimitError as e:
logger.error(f"❌ Rate Limit Error: {e.message}")
logger.info("💡 Tip: Wait a few minutes and try again, or use a paid API plan.")
sys.exit(1)
except AutoPPTError as e:
logger.error(f"❌ AutoPPT Error: {e}")
sys.exit(1)
except KeyboardInterrupt:
logger.warning("\n⚠️ Generation interrupted by user.")
sys.exit(130)
except Exception as e:
logger.error(f"❌ Unexpected Error: {e}")
if args.verbose:
import traceback
traceback.print_exc()
logger.info("💡 Tip: Run with -v flag for detailed error information.")
sys.exit(1)
if __name__ == "__main__":
main()
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/ppt_renderer.py | Python | import os
import logging
from typing import Optional, List, Dict, Any
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from .data_types import UserPresentation, SlideConfig
logger = logging.getLogger(__name__)
class PPTRenderer:
def __init__(self, template_path: str = None):
if template_path:
self.prs = Presentation(template_path)
else:
self.prs = Presentation()
def add_title_slide(self, title: str, subtitle: str = ""):
"""Add a title slide with styled colors."""
slide_layout = self.prs.slide_layouts[0]
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
title_shape = slide.shapes.title
subtitle_shape = slide.placeholders[1]
title_shape.text = title
self._style_text_shape(title_shape, is_title=True)
subtitle_shape.text = subtitle
self._style_text_shape(subtitle_shape, is_title=False)
# Add decoration line for themes that support it
self._add_decoration_line(slide, y_position=3.5)
def add_section_header(self, title: str):
"""Add a section header slide."""
slide_layout = self.prs.slide_layouts[2] # Usually Section Header
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
if slide.shapes.title:
slide.shapes.title.text = title
self._style_text_shape(slide.shapes.title, is_title=True)
def apply_style(self, style_name: str) -> None:
"""Setup global presentation style (colors, fonts)."""
styles = {
"technology": {
"title_color": RGBColor(0, 102, 204),
"text_color": RGBColor(200, 200, 255),
"font_name": "Arial",
"bg_color": RGBColor(10, 10, 40),
"accent_color": RGBColor(0, 150, 255),
"gradient": True,
"gradient_end": RGBColor(30, 30, 80)
},
"nature": {
"title_color": RGBColor(34, 139, 34),
"text_color": RGBColor(50, 80, 50),
"font_name": "Georgia",
"bg_color": RGBColor(245, 255, 250),
"accent_color": RGBColor(60, 179, 113),
"gradient": False
},
"creative": {
"title_color": RGBColor(200, 50, 150),
"text_color": RGBColor(60, 40, 60),
"font_name": "Verdana",
"bg_color": RGBColor(255, 250, 240),
"accent_color": RGBColor(255, 105, 180),
"gradient": False
},
"minimalist": {
"title_color": RGBColor(40, 40, 40),
"text_color": RGBColor(80, 80, 80),
"font_name": "Arial",
"bg_color": RGBColor(255, 255, 255),
"accent_color": RGBColor(100, 100, 100),
"gradient": False
},
"corporate": {
"title_color": RGBColor(0, 51, 102),
"text_color": RGBColor(51, 51, 51),
"font_name": "Calibri",
"bg_color": RGBColor(240, 248, 255),
"accent_color": RGBColor(0, 102, 153),
"gradient": False
},
"academic": {
"title_color": RGBColor(128, 0, 32),
"text_color": RGBColor(64, 64, 64),
"font_name": "Times New Roman",
"bg_color": RGBColor(255, 253, 245),
"accent_color": RGBColor(139, 69, 19),
"gradient": False
},
"startup": {
"title_color": RGBColor(255, 87, 51),
"text_color": RGBColor(51, 51, 51),
"font_name": "Helvetica",
"bg_color": RGBColor(250, 250, 250),
"accent_color": RGBColor(255, 140, 0),
"gradient": False
},
"dark": {
"title_color": RGBColor(0, 200, 150),
"text_color": RGBColor(200, 200, 200),
"font_name": "Consolas",
"bg_color": RGBColor(20, 20, 30),
"accent_color": RGBColor(138, 43, 226),
"gradient": True,
"gradient_end": RGBColor(40, 20, 60)
},
# ========== NEW MODERN THEMES (v0.4) ==========
"luxury": {
"title_color": RGBColor(212, 175, 55), # Gold
"text_color": RGBColor(240, 240, 240),
"font_name": "Georgia",
"bg_color": RGBColor(25, 25, 35),
"accent_color": RGBColor(180, 140, 40),
"gradient": True,
"gradient_end": RGBColor(45, 35, 55),
"decoration_line": True
},
"magazine": {
"title_color": RGBColor(220, 20, 60), # Crimson
"text_color": RGBColor(30, 30, 30),
"font_name": "Helvetica",
"bg_color": RGBColor(255, 255, 255),
"accent_color": RGBColor(220, 20, 60),
"gradient": False,
"decoration_line": True
},
"tech_gradient": {
"title_color": RGBColor(255, 255, 255),
"text_color": RGBColor(230, 230, 250),
"font_name": "Arial",
"bg_color": RGBColor(63, 81, 181), # Indigo
"accent_color": RGBColor(0, 188, 212), # Cyan
"gradient": True,
"gradient_end": RGBColor(156, 39, 176), # Purple
"decoration_line": True
},
"ocean": {
"title_color": RGBColor(255, 255, 255),
"text_color": RGBColor(220, 240, 255),
"font_name": "Arial",
"bg_color": RGBColor(0, 105, 148),
"accent_color": RGBColor(0, 200, 200),
"gradient": True,
"gradient_end": RGBColor(0, 50, 100),
"decoration_line": False
},
"sunset": {
"title_color": RGBColor(255, 255, 255),
"text_color": RGBColor(255, 240, 220),
"font_name": "Georgia",
"bg_color": RGBColor(255, 100, 80),
"accent_color": RGBColor(255, 200, 100),
"gradient": True,
"gradient_end": RGBColor(180, 50, 100),
"decoration_line": True
}
}
self.current_style = styles.get(style_name.lower(), styles["minimalist"])
logger.info(f"Applied theme: {style_name}")
def _apply_background(self, slide):
"""Apply the current style's background color or gradient."""
if not hasattr(self, 'current_style'):
return
# Check if gradient is enabled for this theme
if self.current_style.get("gradient") and "gradient_end" in self.current_style:
try:
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.oxml.ns import qn
from pptx.oxml import parse_xml
# Apply gradient background using XML manipulation
bg = slide.background
bg.fill.gradient()
bg.fill.gradient_angle = 270 # Top to bottom
bg.fill.gradient_stops[0].color.rgb = self.current_style["bg_color"]
bg.fill.gradient_stops[1].color.rgb = self.current_style["gradient_end"]
except Exception as e:
# Fallback to solid color if gradient fails
logger.debug(f"Gradient fallback: {e}")
slide.background.fill.solid()
slide.background.fill.fore_color.rgb = self.current_style["bg_color"]
else:
slide.background.fill.solid()
slide.background.fill.fore_color.rgb = self.current_style["bg_color"]
def _add_decoration_line(self, slide, y_position: float = 1.2):
"""Add a decorative accent line below the title."""
if not hasattr(self, 'current_style'):
return
if not self.current_style.get("decoration_line", False):
return
from pptx.enum.shapes import MSO_SHAPE
# Add a thin accent line
line = slide.shapes.add_shape(
MSO_SHAPE.RECTANGLE,
Inches(0.5), # Left
Inches(y_position), # Top (below title)
Inches(2), # Width
Inches(0.05) # Height (thin line)
)
line.fill.solid()
line.fill.fore_color.rgb = self.current_style["accent_color"]
line.line.fill.background() # No border
def _style_text_shape(self, shape, is_title=False):
"""Apply colors and fonts to a shape's text."""
if not hasattr(self, 'current_style') or not shape.has_text_frame:
return
color = self.current_style["title_color"] if is_title else self.current_style["text_color"]
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
run.font.name = self.current_style["font_name"]
run.font.color.rgb = color
def add_content_slide(self, title: str, bullets: list, notes: str = "", image_path: str = None):
slide_layout = self.prs.slide_layouts[1] # 1 is usually Title and Content
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
# Title
title_shape = slide.shapes.title
title_shape.text = title
self._style_text_shape(title_shape, is_title=True)
# Content (Bullets)
body_shape = slide.placeholders[1]
# If image, we resize the body shape to make room
if image_path and os.path.exists(image_path):
body_shape.width = Inches(5.5)
try:
slide.shapes.add_picture(image_path, Inches(6), Inches(1.5), height=Inches(5))
except Exception as e:
logger.warning(f"Failed to add image {image_path}: {e}")
tf = body_shape.text_frame
tf.word_wrap = True
tf.clear()
for bullet in bullets:
p = tf.add_paragraph()
p.text = bullet
p.level = 0
self._style_text_shape(body_shape, is_title=False)
# Add Notes
if notes:
notes_slide = slide.notes_slide
text_frame = notes_slide.notes_text_frame
text_frame.text = notes
def add_chart_slide(self, title: str, chart_data: 'ChartData', notes: str = "") -> None:
"""
Add a slide with a chart visualization.
Supports bar, pie, line, and column charts.
"""
from .data_types import ChartType
slide_layout = self.prs.slide_layouts[5] # Blank layout for more space
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
# Add title manually
from pptx.util import Inches, Pt
title_box = slide.shapes.add_textbox(Inches(0.5), Inches(0.3), Inches(9), Inches(0.8))
tf = title_box.text_frame
tf.text = title
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(28)
paragraph.font.bold = True
if hasattr(self, 'current_style'):
paragraph.font.color.rgb = self.current_style["title_color"]
# Prepare chart data
chart_data_obj = CategoryChartData()
chart_data_obj.categories = chart_data.categories
chart_data_obj.add_series(chart_data.series_name, chart_data.values)
# Map chart type to python-pptx enum
chart_type_map = {
ChartType.BAR: XL_CHART_TYPE.BAR_CLUSTERED,
ChartType.COLUMN: XL_CHART_TYPE.COLUMN_CLUSTERED,
ChartType.LINE: XL_CHART_TYPE.LINE,
ChartType.PIE: XL_CHART_TYPE.PIE,
}
xl_chart_type = chart_type_map.get(chart_data.chart_type, XL_CHART_TYPE.COLUMN_CLUSTERED)
# Add chart
x, y, cx, cy = Inches(1), Inches(1.5), Inches(8), Inches(5)
chart = slide.shapes.add_chart(xl_chart_type, x, y, cx, cy, chart_data_obj).chart
# Style the chart title
chart.has_title = True
chart.chart_title.text_frame.text = chart_data.title
logger.info(f"Added {chart_data.chart_type.value} chart: {chart_data.title}")
# Add Notes
if notes:
notes_slide = slide.notes_slide
text_frame = notes_slide.notes_text_frame
text_frame.text = notes
def add_citations_slide(self, citations: List[str]) -> None:
"""Add a references/citations slide."""
if not citations:
return
slide_layout = self.prs.slide_layouts[1]
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
title_shape = slide.shapes.title
title_shape.text = "References"
self._style_text_shape(title_shape, is_title=True)
body_shape = slide.placeholders[1]
tf = body_shape.text_frame
tf.clear()
for cit in citations:
p = tf.add_paragraph()
p.text = cit
p.font.size = Pt(12)
self._style_text_shape(body_shape, is_title=False)
logger.info(f"Added citations slide with {len(citations)} references")
def add_fullscreen_image_slide(self, image_path: str, caption: str = "", overlay_title: str = "") -> None:
"""
Add a fullscreen image slide for visual impact (great for section openers).
Args:
image_path: Path to the image file
caption: Optional small caption at the bottom
overlay_title: Optional large title overlaid on the image
"""
if not image_path or not os.path.exists(image_path):
logger.warning(f"Image not found: {image_path}")
return
slide_layout = self.prs.slide_layouts[6] # Blank layout
slide = self.prs.slides.add_slide(slide_layout)
# Add fullscreen image
try:
slide.shapes.add_picture(
image_path,
Inches(0), Inches(0),
width=self.prs.slide_width,
height=self.prs.slide_height
)
except Exception as e:
logger.error(f"Failed to add fullscreen image: {e}")
return
# Add overlay title if provided
if overlay_title:
title_box = slide.shapes.add_textbox(
Inches(0.5), Inches(3),
Inches(9), Inches(1.5)
)
tf = title_box.text_frame
tf.text = overlay_title
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(48)
paragraph.font.bold = True
paragraph.font.color.rgb = RGBColor(255, 255, 255)
# Add shadow effect via font name styling
if hasattr(self, 'current_style'):
paragraph.font.name = self.current_style["font_name"]
# Add caption if provided
if caption:
caption_box = slide.shapes.add_textbox(
Inches(0.5), Inches(6.5),
Inches(9), Inches(0.5)
)
tf = caption_box.text_frame
tf.text = caption
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(14)
paragraph.font.color.rgb = RGBColor(220, 220, 220)
logger.info(f"Added fullscreen image slide: {overlay_title or 'No title'}")
def add_statistics_slide(self, title: str, stats: List[Dict[str, str]], notes: str = "") -> None:
"""
Add a slide highlighting key statistics with large numbers.
Args:
title: Slide title
stats: List of dicts with 'value' (e.g., "85%") and 'label' (e.g., "Market Share")
notes: Optional speaker notes
"""
slide_layout = self.prs.slide_layouts[6] # Blank layout
slide = self.prs.slides.add_slide(slide_layout)
self._apply_background(slide)
# Add title at top
title_box = slide.shapes.add_textbox(
Inches(0.5), Inches(0.3),
Inches(9), Inches(0.8)
)
tf = title_box.text_frame
tf.text = title
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(32)
paragraph.font.bold = True
if hasattr(self, 'current_style'):
paragraph.font.color.rgb = self.current_style["title_color"]
paragraph.font.name = self.current_style["font_name"]
# Calculate positions for stats (distribute evenly)
num_stats = min(len(stats), 4) # Max 4 stats
if num_stats == 0:
return
spacing = 9 / num_stats
start_x = 0.5 + (spacing - 2) / 2 # Center each stat box
for i, stat in enumerate(stats[:4]):
x_pos = start_x + (i * spacing)
# Large number
value_box = slide.shapes.add_textbox(
Inches(x_pos), Inches(2.5),
Inches(2), Inches(1.5)
)
tf = value_box.text_frame
tf.text = stat.get("value", "N/A")
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(54)
paragraph.font.bold = True
if hasattr(self, 'current_style'):
paragraph.font.color.rgb = self.current_style["accent_color"]
paragraph.font.name = self.current_style["font_name"]
# Label below
label_box = slide.shapes.add_textbox(
Inches(x_pos), Inches(4.2),
Inches(2), Inches(0.8)
)
tf = label_box.text_frame
tf.text = stat.get("label", "")
tf.word_wrap = True
for paragraph in tf.paragraphs:
paragraph.font.size = Pt(16)
if hasattr(self, 'current_style'):
paragraph.font.color.rgb = self.current_style["text_color"]
paragraph.font.name = self.current_style["font_name"]
# Add notes
if notes:
notes_slide = slide.notes_slide
text_frame = notes_slide.notes_text_frame
text_frame.text = notes
logger.info(f"Added statistics slide: {title} with {num_stats} stats")
def save(self, output_path: str) -> None:
"""Save the presentation to a file."""
self.prs.save(output_path)
logger.info(f"Saved presentation to {output_path}")
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
autoppt/researcher.py | Python | import logging
import time
from typing import List, Dict, Optional
import requests
from ddgs import DDGS
from .config import Config
from .exceptions import ResearchError
logger = logging.getLogger(__name__)
class Researcher:
"""Research module for gathering web content and images."""
def __init__(self):
self.ddgs = DDGS()
def search(self, query: str, max_results: int = 3) -> List[Dict[str, str]]:
"""
Perform a web search and return a list of results.
Each result contains 'title', 'href', and 'body'.
"""
logger.info(f"Searching for: {query}")
try:
results = list(self.ddgs.text(query, max_results=max_results))
clean_results = []
for r in results:
clean_results.append({
"title": r.get("title", ""),
"href": r.get("href", ""),
"body": r.get("body", "")
})
logger.debug(f"Found {len(clean_results)} results for '{query}'")
return clean_results
except Exception as e:
logger.error(f"Error searching for '{query}': {e}")
return []
def search_wikipedia(self, query: str, sentences: int = 5) -> Optional[Dict[str, str]]:
"""
Search Wikipedia for a topic and return a summary.
Returns a dict with 'title', 'summary', and 'url'.
"""
logger.info(f"Searching Wikipedia for: {query}")
try:
import wikipedia
wikipedia.set_lang("en")
# Search for the most relevant page
search_results = wikipedia.search(query, results=1)
if not search_results:
logger.warning(f"No Wikipedia results for '{query}'")
return None
page_title = search_results[0]
page = wikipedia.page(page_title, auto_suggest=False)
summary = wikipedia.summary(page_title, sentences=sentences)
return {
"title": page.title,
"summary": summary,
"url": page.url
}
except Exception as e:
logger.warning(f"Wikipedia search failed for '{query}': {e}")
return None
def search_images(self, query: str, max_results: int = 1) -> List[Dict[str, str]]:
"""
Perform a web search for images and return a list of results.
"""
logger.info(f"Searching images for: {query}")
try:
results = list(self.ddgs.images(query, max_results=max_results))
clean_results = []
for r in results:
clean_results.append({
"title": r.get("title", ""),
"image": r.get("image", ""),
"thumbnail": r.get("thumbnail", ""),
"url": r.get("url", "")
})
return clean_results
except Exception as e:
logger.error(f"Error searching images for '{query}': {e}")
return []
def download_image(self, url: str, save_path: str, retries: int = 3) -> bool:
"""
Download an image from a URL and save it to the specified path.
Includes retry logic for improved stability.
"""
for attempt in range(retries):
try:
response = requests.get(url, timeout=Config.IMAGE_DOWNLOAD_TIMEOUT)
if response.status_code == 200:
with open(save_path, 'wb') as f:
f.write(response.content)
logger.debug(f"Downloaded image to {save_path}")
return True
else:
logger.warning(f"Image download returned status {response.status_code}")
except Exception as e:
logger.warning(f"Image download attempt {attempt+1}/{retries} failed: {e}")
if attempt < retries - 1:
time.sleep(2)
return False
def gather_context(self, queries: List[str], include_wikipedia: bool = True) -> str:
"""
Run multiple queries and aggregate the results into a single context string.
Combines DuckDuckGo web search with Wikipedia for richer content.
Returns a formatted string suitable for LLM context.
"""
aggregated_context = ""
seen_urls = set()
for q in queries:
# Web search results
results = self.search(q)
for r in results:
if r['href'] not in seen_urls:
aggregated_context += f"Source: {r['title']} ({r['href']})\nContent: {r['body']}\n\n"
seen_urls.add(r['href'])
# Wikipedia enhancement
if include_wikipedia:
wiki_result = self.search_wikipedia(q)
if wiki_result and wiki_result['url'] not in seen_urls:
aggregated_context += f"Wikipedia: {wiki_result['title']} ({wiki_result['url']})\nSummary: {wiki_result['summary']}\n\n"
seen_urls.add(wiki_result['url'])
logger.info(f"Gathered context from {len(seen_urls)} unique sources")
return aggregated_context
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
scripts/check_sensitive.py | Python | #!/usr/bin/env python3
"""
Safety check script for AutoPPT.
Checks for sensitive information (API keys, local paths) and unwanted files.
"""
import os
import sys
import re
import subprocess
# Patterns to search for
SENSITIVE_PATTERNS = [
(r"sk-[a-zA-Z0-9]{32,}", "Potential OpenAI/Anthropic API Key"),
(r"AIza[0-9A-Za-z-_]{35}", "Potential Google API Key"),
(r"/Users/baohua", "Local user path leakage"),
(r"\"(http|https)://[^\"]*:[^\"]*@\"", "Hardcoded credentials in URL"),
]
UNWANTED_EXTENSIONS = [".log", ".tmp", ".temp"]
UNWANTED_FILES = ["sample_output.pptx", "test.pptx"]
def check_files():
print("🔍 Running safety audit...")
errors = 0
# Check for unwanted files in Git index
try:
git_files = subprocess.check_output(["git", "ls-files"]).decode("utf-8").splitlines()
except Exception:
git_files = []
for file_path in git_files:
if "check_sensitive.py" in file_path:
continue
# Check extensions
_, ext = os.path.splitext(file_path)
if ext in UNWANTED_EXTENSIONS or os.path.basename(file_path) in UNWANTED_FILES:
print(f"❌ Unwanted file found in index: {file_path}")
errors += 1
# Check content of text files
if ext in [".py", ".md", ".txt", ".json", ".yaml", ".yml", ".toml"]:
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
for pattern, description in SENSITIVE_PATTERNS:
if re.search(pattern, content):
print(f"❌ {description} found in: {file_path}")
errors += 1
except Exception as e:
print(f"⚠️ Could not read {file_path}: {e}")
if errors == 0:
print("✅ Safety audit passed! No sensitive data or unwanted files detected.")
return True
else:
print(f"🚨 Safety audit failed with {errors} errors.")
return False
if __name__ == "__main__":
if not check_files():
sys.exit(1)
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
scripts/generate_sample.py | Python | import sys
import os
# Add parent directory to path so we can import core
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core.ppt_renderer import PPTRenderer
def generate_sample():
print("Generating sample PPT from hardcoded data...")
renderer = PPTRenderer()
# Title Slide
renderer.add_title_slide("Sample Presentation", "Generated by Auto PPT Generator")
# Slide 1
renderer.add_content_slide(
"Introduction",
[
"This is a sample presentation.",
"It was generated without using an LLM.",
"It demonstrates the layout and structure."
],
notes="Speaker notes would go here."
)
# Slide 2
renderer.add_content_slide(
"Features",
[
"Automated content generation",
"Support for OpenAI, Anthropic, and Google",
"Clean minimalist design"
]
)
# Citations
renderer.add_citations_slide([
"https://example.com/source1",
"https://example.com/source2"
])
output_path = "samples/sample.pptx"
renderer.save(output_path)
print(f"Sample saved to {output_path}")
if __name__ == "__main__":
generate_sample()
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
scripts/install_hooks.py | Python | #!/usr/bin/env python3
"""
Installer for AutoPPT Git hooks.
Sets up the pre-commit hook to run safety audits automatically.
"""
import os
import stat
HOOK_CONTENT = """#!/bin/bash
echo "🛡️ Running pre-commit safety audit..."
python3 scripts/check_sensitive.py
if [ $? -ne 0 ]; then
echo "🚨 Commit aborted. Please fix the security/cleanup issues above."
exit 1
fi
echo "🧪 Running unit tests..."
export PYTHONPATH=$PYTHONPATH:.
pytest tests/ -q
if [ $? -ne 0 ]; then
echo "🚨 Commit aborted. Some tests failed."
exit 1
fi
echo "✅ All checks passed. Proceeding with commit."
exit 0
"""
def install_hook():
hook_path = ".git/hooks/pre-commit"
if not os.path.exists(".git"):
print("❌ Error: .git directory not found. Are you in the project root?")
return
with open(hook_path, "w") as f:
f.write(HOOK_CONTENT)
# Make executable
st = os.stat(hook_path)
os.chmod(hook_path, st.st_mode | stat.S_IEXEC)
print(f"✅ Git pre-commit hook installed at {hook_path}")
if __name__ == "__main__":
install_hook()
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/__init__.py | Python | # Tests package
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/conftest.py | Python | """
Pytest configuration and shared fixtures for AutoPPT tests.
"""
import pytest
import os
import sys
import tempfile
import shutil
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@pytest.fixture
def temp_dir():
"""Create a temporary directory for test outputs."""
dirpath = tempfile.mkdtemp()
yield dirpath
shutil.rmtree(dirpath)
@pytest.fixture
def sample_topic():
"""Return a sample topic for testing."""
return "Artificial Intelligence"
@pytest.fixture
def sample_bullets():
"""Return sample bullet points for testing."""
return [
"First key point about the topic",
"Second important insight",
"Third critical observation"
]
@pytest.fixture
def mock_search_results():
"""Return mock search results for testing."""
return [
{
"title": "Test Article 1",
"href": "https://example.com/article1",
"body": "This is the body content of article 1."
},
{
"title": "Test Article 2",
"href": "https://example.com/article2",
"body": "This is the body content of article 2."
}
]
@pytest.fixture
def mock_wiki_result():
"""Return mock Wikipedia result for testing."""
return {
"title": "Artificial Intelligence",
"summary": "Artificial intelligence (AI) is intelligence demonstrated by machines.",
"url": "https://en.wikipedia.org/wiki/Artificial_intelligence"
}
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/test_data_types.py | Python | """
Unit tests for data types (Pydantic models).
"""
import pytest
from pydantic import ValidationError
from autoppt.data_types import (
ChartType,
ChartData,
SlideConfig,
PresentationSection,
PresentationOutline,
UserPresentation
)
class TestChartType:
"""Tests for ChartType enum."""
def test_chart_types_exist(self):
"""Test that all expected chart types exist."""
assert ChartType.BAR == "bar"
assert ChartType.PIE == "pie"
assert ChartType.LINE == "line"
assert ChartType.COLUMN == "column"
class TestChartData:
"""Tests for ChartData model."""
def test_valid_chart_data(self):
"""Test creating valid ChartData."""
chart = ChartData(
chart_type=ChartType.BAR,
title="Sales by Region",
categories=["North", "South", "East", "West"],
values=[100.0, 200.0, 150.0, 180.0]
)
assert chart.chart_type == ChartType.BAR
assert chart.title == "Sales by Region"
assert len(chart.categories) == 4
assert len(chart.values) == 4
assert chart.series_name == "Series 1" # Default value
def test_chart_data_custom_series_name(self):
"""Test ChartData with custom series name."""
chart = ChartData(
chart_type=ChartType.PIE,
title="Market Share",
categories=["A", "B", "C"],
values=[50.0, 30.0, 20.0],
series_name="2025 Data"
)
assert chart.series_name == "2025 Data"
class TestSlideConfig:
"""Tests for SlideConfig model."""
def test_minimal_slide_config(self):
"""Test SlideConfig with minimal required fields."""
slide = SlideConfig(
title="Introduction",
bullets=["Point 1", "Point 2", "Point 3"]
)
assert slide.title == "Introduction"
assert len(slide.bullets) == 3
assert slide.image_query is None
assert slide.speaker_notes is None
assert slide.citations == []
assert slide.chart_data is None
def test_full_slide_config(self):
"""Test SlideConfig with all fields."""
chart = ChartData(
chart_type=ChartType.LINE,
title="Growth Trend",
categories=["Q1", "Q2", "Q3", "Q4"],
values=[10.0, 25.0, 40.0, 60.0]
)
slide = SlideConfig(
title="Market Analysis",
bullets=["Growth is accelerating", "Q4 shows 50% increase"],
image_query="business growth chart abstract",
speaker_notes="Discuss the quarterly growth patterns.",
citations=["https://example.com/report"],
chart_data=chart
)
assert slide.title == "Market Analysis"
assert slide.image_query is not None
assert slide.speaker_notes is not None
assert len(slide.citations) == 1
assert slide.chart_data is not None
assert slide.chart_data.chart_type == ChartType.LINE
def test_slide_config_missing_required_fields(self):
"""Test that missing required fields raises error."""
with pytest.raises(ValidationError):
SlideConfig(title="Only Title") # Missing bullets
class TestPresentationSection:
"""Tests for PresentationSection model."""
def test_valid_section(self):
"""Test creating valid PresentationSection."""
section = PresentationSection(
title="Introduction",
slides=["Overview", "Background", "Objectives"]
)
assert section.title == "Introduction"
assert len(section.slides) == 3
class TestPresentationOutline:
"""Tests for PresentationOutline model."""
def test_valid_outline(self):
"""Test creating valid PresentationOutline."""
outline = PresentationOutline(
title="AI in Healthcare",
sections=[
PresentationSection(title="Introduction", slides=["Overview"]),
PresentationSection(title="Applications", slides=["Diagnosis", "Treatment"]),
PresentationSection(title="Conclusion", slides=["Summary", "Future"])
]
)
assert outline.title == "AI in Healthcare"
assert len(outline.sections) == 3
assert outline.sections[1].title == "Applications"
class TestUserPresentation:
"""Tests for UserPresentation model."""
def test_valid_user_presentation(self):
"""Test creating valid UserPresentation."""
presentation = UserPresentation(
title="My Presentation",
sections=[
PresentationSection(title="Part 1", slides=["Slide A"]),
PresentationSection(title="Part 2", slides=["Slide B"])
]
)
assert presentation.title == "My Presentation"
assert len(presentation.sections) == 2
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/test_llm_provider.py | Python | """
Unit tests for LLM providers.
"""
import pytest
from typing import List
from autoppt.llm_provider import (
BaseLLMProvider,
MockProvider,
get_provider
)
from autoppt.data_types import (
PresentationOutline,
PresentationSection,
SlideConfig
)
class TestMockProvider:
"""Tests for MockProvider class."""
def test_mock_provider_instantiation(self):
"""Test that MockProvider can be instantiated."""
provider = MockProvider()
assert provider is not None
assert isinstance(provider, BaseLLMProvider)
def test_generate_text(self):
"""Test generate_text returns a string."""
provider = MockProvider()
result = provider.generate_text("Test prompt")
assert isinstance(result, str)
assert len(result) > 0
assert "content" in result.lower() or "presentation" in result.lower()
def test_generate_structure_outline(self):
"""Test generate_structure returns valid PresentationOutline."""
provider = MockProvider()
prompt = "Create outline for topic: Quantum Computing"
result = provider.generate_structure(prompt, PresentationOutline)
assert isinstance(result, PresentationOutline)
assert isinstance(result.title, str)
assert len(result.title) > 0
assert isinstance(result.sections, list)
assert len(result.sections) > 0
for section in result.sections:
assert isinstance(section, PresentationSection)
assert isinstance(section.title, str)
assert isinstance(section.slides, list)
def test_generate_structure_slide_config(self):
"""Test generate_structure returns valid SlideConfig."""
provider = MockProvider()
prompt = "Create slide about Machine Learning"
result = provider.generate_structure(prompt, SlideConfig)
assert isinstance(result, SlideConfig)
assert isinstance(result.title, str)
assert isinstance(result.bullets, list)
assert len(result.bullets) > 0
class TestGetProvider:
"""Tests for get_provider factory function."""
def test_get_mock_provider(self):
"""Test getting mock provider."""
provider = get_provider("mock")
assert isinstance(provider, MockProvider)
def test_get_provider_case_insensitive(self):
"""Test that provider names are case-insensitive."""
provider1 = get_provider("Mock")
provider2 = get_provider("MOCK")
provider3 = get_provider("mock")
assert isinstance(provider1, MockProvider)
assert isinstance(provider2, MockProvider)
assert isinstance(provider3, MockProvider)
def test_get_unknown_provider_raises(self):
"""Test that unknown provider raises ValueError."""
with pytest.raises(ValueError) as exc_info:
get_provider("unknown_provider")
assert "Unknown provider" in str(exc_info.value)
assert "unknown_provider" in str(exc_info.value)
class TestProviderInterface:
"""Tests for BaseLLMProvider interface compliance."""
def test_mock_provider_has_required_methods(self):
"""Test MockProvider has all required methods."""
provider = MockProvider()
assert hasattr(provider, 'generate_text')
assert hasattr(provider, 'generate_structure')
assert callable(provider.generate_text)
assert callable(provider.generate_structure)
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/test_renderer.py | Python | """
Unit tests for PPT renderer.
"""
import pytest
import os
import tempfile
from autoppt.ppt_renderer import PPTRenderer
from autoppt.data_types import ChartData, ChartType
class TestPPTRendererInit:
"""Tests for PPTRenderer initialization."""
def test_renderer_instantiation(self):
"""Test that PPTRenderer can be instantiated."""
renderer = PPTRenderer()
assert renderer is not None
assert renderer.prs is not None
def test_renderer_with_no_template(self):
"""Test renderer creates empty presentation without template."""
renderer = PPTRenderer(template_path=None)
assert len(renderer.prs.slides) == 0
class TestApplyStyle:
"""Tests for apply_style method."""
def test_apply_minimalist_style(self):
"""Test applying minimalist style."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
assert hasattr(renderer, 'current_style')
assert 'title_color' in renderer.current_style
assert 'text_color' in renderer.current_style
assert 'bg_color' in renderer.current_style
assert 'font_name' in renderer.current_style
def test_apply_all_styles(self):
"""Test that all styles can be applied without error."""
styles = [
"minimalist", "technology", "nature", "creative",
"corporate", "academic", "startup", "dark"
]
for style in styles:
renderer = PPTRenderer()
renderer.apply_style(style)
assert hasattr(renderer, 'current_style')
def test_apply_unknown_style_defaults(self):
"""Test that unknown style defaults to minimalist."""
renderer = PPTRenderer()
renderer.apply_style("unknown_style")
# Should not raise, should default to minimalist
assert hasattr(renderer, 'current_style')
class TestAddSlides:
"""Tests for slide addition methods."""
def test_add_title_slide(self):
"""Test adding a title slide."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
initial_count = len(renderer.prs.slides)
renderer.add_title_slide("Test Title", "Test Subtitle")
assert len(renderer.prs.slides) == initial_count + 1
def test_add_section_header(self):
"""Test adding a section header slide."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
initial_count = len(renderer.prs.slides)
renderer.add_section_header("Section 1")
assert len(renderer.prs.slides) == initial_count + 1
def test_add_content_slide(self, sample_bullets):
"""Test adding a content slide with bullets."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
initial_count = len(renderer.prs.slides)
renderer.add_content_slide(
title="Content Slide",
bullets=sample_bullets,
notes="Speaker notes here"
)
assert len(renderer.prs.slides) == initial_count + 1
def test_add_citations_slide(self):
"""Test adding a citations slide."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
citations = [
"https://example.com/source1",
"https://example.com/source2"
]
initial_count = len(renderer.prs.slides)
renderer.add_citations_slide(citations)
assert len(renderer.prs.slides) == initial_count + 1
def test_add_citations_slide_empty_list(self):
"""Test that empty citations list adds no slide."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
initial_count = len(renderer.prs.slides)
renderer.add_citations_slide([])
assert len(renderer.prs.slides) == initial_count
class TestChartSlide:
"""Tests for chart slide functionality."""
def test_add_chart_slide(self):
"""Test adding a chart slide."""
renderer = PPTRenderer()
renderer.apply_style("corporate")
chart_data = ChartData(
chart_type=ChartType.COLUMN,
title="Quarterly Revenue",
categories=["Q1", "Q2", "Q3", "Q4"],
values=[100.0, 150.0, 200.0, 250.0],
series_name="2025"
)
initial_count = len(renderer.prs.slides)
renderer.add_chart_slide("Revenue Analysis", chart_data)
assert len(renderer.prs.slides) == initial_count + 1
class TestSave:
"""Tests for save functionality."""
def test_save_presentation(self, temp_dir, sample_bullets):
"""Test saving a presentation to file."""
renderer = PPTRenderer()
renderer.apply_style("minimalist")
renderer.add_title_slide("Test Presentation", "Subtitle")
renderer.add_section_header("Section 1")
renderer.add_content_slide("Slide 1", sample_bullets)
output_path = os.path.join(temp_dir, "test_output.pptx")
renderer.save(output_path)
assert os.path.exists(output_path)
assert os.path.getsize(output_path) > 0
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
tests/test_researcher.py | Python | """
Unit tests for Researcher module.
"""
import pytest
from unittest.mock import patch, MagicMock
from autoppt.researcher import Researcher
class TestResearcherInit:
"""Tests for Researcher initialization."""
def test_researcher_instantiation(self):
"""Test that Researcher can be instantiated."""
researcher = Researcher()
assert researcher is not None
assert researcher.ddgs is not None
class TestSearchMethods:
"""Tests for search methods with mocking."""
@patch.object(Researcher, 'search')
def test_search_returns_list(self, mock_search, mock_search_results):
"""Test that search returns a list of results."""
mock_search.return_value = mock_search_results
researcher = Researcher()
results = researcher.search("test query")
assert isinstance(results, list)
assert len(results) == 2
assert 'title' in results[0]
assert 'href' in results[0]
assert 'body' in results[0]
@patch.object(Researcher, 'search_wikipedia')
def test_search_wikipedia_returns_dict(self, mock_wiki, mock_wiki_result):
"""Test that search_wikipedia returns a dictionary."""
mock_wiki.return_value = mock_wiki_result
researcher = Researcher()
result = researcher.search_wikipedia("Artificial Intelligence")
assert isinstance(result, dict)
assert 'title' in result
assert 'summary' in result
assert 'url' in result
@patch.object(Researcher, 'search_images')
def test_search_images_returns_list(self, mock_images):
"""Test that search_images returns a list."""
mock_images.return_value = [
{"title": "Image 1", "image": "https://example.com/img1.jpg"}
]
researcher = Researcher()
results = researcher.search_images("technology abstract")
assert isinstance(results, list)
class TestGatherContext:
"""Tests for gather_context method."""
@patch.object(Researcher, 'search')
@patch.object(Researcher, 'search_wikipedia')
def test_gather_context_combines_sources(
self, mock_wiki, mock_search, mock_search_results, mock_wiki_result
):
"""Test that gather_context combines web and wiki sources."""
mock_search.return_value = mock_search_results
mock_wiki.return_value = mock_wiki_result
researcher = Researcher()
context = researcher.gather_context(["AI applications"])
assert isinstance(context, str)
assert len(context) > 0
@patch.object(Researcher, 'search')
@patch.object(Researcher, 'search_wikipedia')
def test_gather_context_deduplicates_urls(
self, mock_wiki, mock_search, mock_search_results, mock_wiki_result
):
"""Test that gather_context deduplicates URLs."""
mock_search.return_value = mock_search_results
mock_wiki.return_value = mock_wiki_result
researcher = Researcher()
# Search same query twice
context = researcher.gather_context(["AI", "AI"])
# Should not have duplicate content
assert isinstance(context, str)
@patch.object(Researcher, 'search')
@patch.object(Researcher, 'search_wikipedia')
def test_gather_context_without_wikipedia(self, mock_wiki, mock_search, mock_search_results):
"""Test gather_context can exclude Wikipedia."""
mock_search.return_value = mock_search_results
mock_wiki.return_value = None
researcher = Researcher()
context = researcher.gather_context(["test"], include_wikipedia=False)
assert isinstance(context, str)
mock_wiki.assert_not_called()
class TestDownloadImage:
"""Tests for download_image method."""
@patch('requests.get')
def test_download_image_success(self, mock_get, temp_dir):
"""Test successful image download."""
# Mock successful response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.content = b'fake image data'
mock_get.return_value = mock_response
researcher = Researcher()
import os
save_path = os.path.join(temp_dir, "test_image.jpg")
result = researcher.download_image("https://example.com/image.jpg", save_path)
assert result is True
assert os.path.exists(save_path)
@patch('requests.get')
def test_download_image_failure(self, mock_get, temp_dir):
"""Test failed image download returns False."""
mock_get.side_effect = Exception("Network error")
researcher = Researcher()
import os
save_path = os.path.join(temp_dir, "test_image.jpg")
result = researcher.download_image("https://example.com/image.jpg", save_path)
assert result is False
| yeasy/AutoPPT | 0 | Generate Professional Presentations in Seconds using latest AI. | Python | yeasy | Baohua Yang | |
cmd/benchmark.go | Go | // Package cmd provides the command line interface logic for ask.
package cmd
import (
"fmt"
"os"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"github.com/yeasy/ask/internal/cache"
"github.com/yeasy/ask/internal/config"
"github.com/yeasy/ask/internal/github"
)
// benchmarkCmd represents the benchmark command
var benchmarkCmd = &cobra.Command{
Use: "benchmark",
Short: "Run performance benchmarks",
Long: `Measure the performance of key CLI operations like search, list, and info.`,
Run: func(_ *cobra.Command, _ []string) {
fmt.Println("Running benchmarks...")
fmt.Println()
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(w, "OPERATION\tTIME\tNOTES")
// 1. Search (Cold) - Clear cache first
c, err := cache.New("", cache.DefaultTTL)
if err == nil {
_ = c.Clear()
}
start := time.Now()
// We simulate search by calling the internal function directly to avoid printing to stdout
// But since searchCmd prints to stdout, we might just want to measure the internal call
// For a real benchmark, we should call the internal functions
// Load config for search
cfg, _ := config.LoadConfig()
if cfg == nil {
def := config.DefaultConfig()
cfg = &def
}
// Mock search execution (Cold)
// We'll search for "browser" which should trigger network requests
repo := cfg.Repos[0] // Use first repo
if repo.Type == "topic" {
_, _ = github.SearchTopic(repo.URL, "browser")
}
duration := time.Since(start)
_, _ = fmt.Fprintf(w, "Search (Cold)\t%v\tFirst repo only\n", duration.Round(time.Millisecond))
// 2. Search (Hot) - Should be cached
start = time.Now()
if repo.Type == "topic" {
_, _ = github.SearchTopic(repo.URL, "browser")
}
duration = time.Since(start)
_, _ = fmt.Fprintf(w, "Search (Hot)\t%v\tCached\n", duration.Round(time.Millisecond))
// 3. List - Local operation
start = time.Now()
// Simulate list parsing
_, _ = config.LoadConfig()
duration = time.Since(start)
_, _ = fmt.Fprintf(w, "List\t%v\tConfig load\n", duration.Round(time.Millisecond))
_ = w.Flush()
fmt.Println()
fmt.Println("Done.")
},
}
func init() {
rootCmd.AddCommand(benchmarkCmd)
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/check.go | Go | package cmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/yeasy/ask/internal/config"
"github.com/yeasy/ask/internal/skill"
)
// checkCmd represents the check command
var checkCmd = &cobra.Command{
Use: "check [skill-path]",
Short: "Check a skill for security issues",
Long: `Analyze a skill directory for potential security risks,
including hardcoded secrets, dangerous commands, and network activity.
If skill-path is not provided, the current directory is checked.
If the current directory is not a skill, all installed skills across all agents are checked.`,
Args: cobra.MaximumNArgs(1),
Run: runCheck,
}
var outputFile string
func init() {
checkCmd.Flags().StringVarP(&outputFile, "output", "o", "", "Write report to file (supports .md, .html/.htm, .json)")
}
func runCheck(_ *cobra.Command, args []string) {
var targetPath string
var err error
// Determine target path
if len(args) > 0 {
targetPath, err = filepath.Abs(args[0])
if err != nil {
fmt.Printf("Error resolving path: %v\n", err)
os.Exit(1)
}
} else {
targetPath, err = os.Getwd()
if err != nil {
fmt.Printf("Error getting current directory: %v\n", err)
os.Exit(1)
}
}
// Check if the target itself is a skill
if skill.FindSkillMD(targetPath) {
if len(args) == 0 {
fmt.Printf("Checking skill in current directory...\n")
}
result, err := checkSingleSkill(targetPath)
if err != nil {
fmt.Printf("Error checking skill: %v\n", err)
os.Exit(1)
}
// Ensure module name is set
for i := range result.Findings {
if result.Findings[i].Module == "" {
result.Findings[i].Module = result.SkillName
}
}
if outputFile != "" {
handleReport(result, outputFile)
} else {
printReport(result)
}
if hasCriticalIssues(result) {
os.Exit(1)
}
return
}
// Not a skill? Scan as a project
label := "project skills"
if len(args) > 0 {
label = args[0]
} else {
fmt.Println("Current directory is not a skill. Scanning project skills...")
}
scanProject(targetPath, label)
}
func formatPathForDisplay(path string) string {
cwd, err := os.Getwd()
if err == nil {
rel, err := filepath.Rel(cwd, path)
if err == nil && !strings.HasPrefix(rel, "..") {
return rel
}
}
home, err := os.UserHomeDir()
if err == nil && strings.HasPrefix(path, home) {
return "~" + strings.TrimPrefix(path, home)
}
return path
}
func checkSingleSkill(absPath string) (*skill.CheckResult, error) {
return skill.CheckSafety(absPath)
}
func hasCriticalIssues(result *skill.CheckResult) bool {
for _, f := range result.Findings {
if f.Severity == skill.SeverityCritical {
return true
}
}
return false
}
func handleReport(result *skill.CheckResult, filename string) {
ext := filepath.Ext(filename)
format := "md"
switch ext {
case ".html", ".htm":
format = "html"
case ".json":
format = "json"
}
content, err := skill.GenerateReport(result, format)
if err != nil {
fmt.Printf("Error generating report: %v\n", err)
os.Exit(1)
}
if err := os.WriteFile(filename, []byte(content), 0644); err != nil {
fmt.Printf("Error writing report to %s: %v\n", filename, err)
os.Exit(1)
}
fmt.Printf("\n%s Security report saved to %s\n", color.GreenString("✓"), filename)
if hasCriticalIssues(result) {
fmt.Printf("%s Found critical issues. Please review the report.\n", color.RedString("!"))
}
}
func printReport(result *skill.CheckResult) {
fmt.Printf("\nSecurity Report for: %s\n", color.CyanString(result.SkillName))
fmt.Println("----------------------------------------")
if len(result.Findings) == 0 {
color.Green("✓ No issues found. Skill appears safe.\n")
return
}
criticals := 0
warnings := 0
infos := 0
for _, finding := range result.Findings {
switch finding.Severity {
case skill.SeverityCritical:
criticals++
printFinding(color.RedString("[CRITICAL]"), finding)
case skill.SeverityWarning:
warnings++
printFinding(color.YellowString("[WARNING] "), finding)
case skill.SeverityInfo:
infos++
printFinding(color.BlueString("[INFO] "), finding)
}
}
fmt.Println("----------------------------------------")
fmt.Printf("Summary: %d Critical, %d Warning, %d Info\n", criticals, warnings, infos)
}
func printCompactReport(result *skill.CheckResult) {
if len(result.Findings) == 0 {
fmt.Printf(" %s %s: No issues\n", color.GreenString("✓"), result.SkillName)
return
}
criticals := 0
warnings := 0
for _, f := range result.Findings {
switch f.Severity {
case skill.SeverityCritical:
criticals++
case skill.SeverityWarning:
warnings++
}
}
if criticals > 0 {
fmt.Printf(" %s %s: %d Critical, %d Warnings\n", color.RedString("!"), result.SkillName, criticals, warnings)
for _, f := range result.Findings {
if f.Severity == skill.SeverityCritical {
fmt.Printf(" - %s: %s\n", f.RuleID, f.Description)
}
}
} else if warnings > 0 {
fmt.Printf(" %s %s: %d Warnings\n", color.YellowString("!"), result.SkillName, warnings)
} else {
// Only info
fmt.Printf(" %s %s: OK (Info only)\n", color.GreenString("✓"), result.SkillName)
}
}
func printFinding(prefix string, finding skill.Finding) {
fmt.Printf("%s %s\n", prefix, finding.Description)
fmt.Printf(" File: %s:%d\n", finding.File, finding.Line)
fmt.Printf(" Match: %s\n\n", finding.Match)
}
// scanProject scans a project root for skills in known directories
func scanProject(rootDir string, label string) {
// Define directories to check. Order matters for precedence implicitly if we were deduplicating skills by name,
// but here we report everything.
// 1. .agent/skills (Default)
// 2. <agent> project dirs (e.g. .claude/skills)
// 3. skills (Generic)
// 4. . (Root - for flat repos)
searchDirs := []string{config.DefaultSkillsDir, "skills", "."}
for _, agentConfig := range config.SupportedAgents {
searchDirs = append(searchDirs, agentConfig.ProjectDir)
}
// Deduplicate search dirs
uniqueDirs := make(map[string]bool)
var dirs []string
for _, d := range searchDirs {
if !uniqueDirs[d] {
uniqueDirs[d] = true
dirs = append(dirs, d)
}
}
foundSkills := 0
issuesFound := false
cwd, _ := os.Getwd()
// Aggregate results
// Use formatted path for display if it looks like a path
displayLabel := label
if filepath.IsAbs(label) || strings.Contains(label, string(os.PathSeparator)) || label == "." {
displayLabel = formatPathForDisplay(label)
}
// If display label resolves to ".", it's confusing in a static report. Use absolute or home-relative path instead.
if displayLabel == "." {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(rootDir, home) {
displayLabel = "~" + strings.TrimPrefix(rootDir, home)
} else {
displayLabel = rootDir
}
}
aggregatedResult := &skill.CheckResult{
SkillName: displayLabel,
Findings: []skill.Finding{},
}
// Track examined paths to avoid duplicate scans if nested dirs overlap
// (e.g. scanning "." and "skills" - "." covers "skills")
scannedPaths := make(map[string]bool)
for _, relDir := range dirs {
startDir := filepath.Join(rootDir, relDir)
// If we already scanned this directory (or a parent of it) as part of "." scan, strictly speaking we might double scan.
// However, "WalkDir" on "." will cover everything.
// If "." is in the list, it effectively supersedes others if they are subdirs of it.
// To keep it simple and robust: we will walk each requested dir.
// Inside walk, we check unique SKILL.md paths.
_ = filepath.WalkDir(startDir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil // Skip errors
}
if d.IsDir() {
// Optimization: Skip .git
if d.Name() == ".git" {
return filepath.SkipDir
}
// Check if this directory is a skill
if skill.FindSkillMD(path) {
// Use absolute path for uniqueness check
absPath, _ := filepath.Abs(path)
if scannedPaths[absPath] {
return filepath.SkipDir // Already scanned this skill
}
scannedPaths[absPath] = true
foundSkills++
displayPath := formatPathForDisplay(path)
fmt.Printf("Checking %s...\n", displayPath)
result, err := checkSingleSkill(path)
if err != nil {
fmt.Printf(" Error checking skill: %v\n", err)
return nil
}
printCompactReport(result)
if hasCriticalIssues(result) {
issuesFound = true
}
// Add to aggregated results
relSkillPath, _ := filepath.Rel(cwd, path)
if relSkillPath == "" || strings.HasPrefix(relSkillPath, "..") {
relSkillPath, _ = filepath.Rel(rootDir, path)
}
if relSkillPath == "" || strings.HasPrefix(relSkillPath, "..") {
relSkillPath = filepath.Base(path)
}
for _, f := range result.Findings {
if f.Module == "" {
f.Module = result.SkillName
}
f.File = filepath.Join(relSkillPath, f.File)
aggregatedResult.Findings = append(aggregatedResult.Findings, f)
}
// Track scanned module
aggregatedResult.ScannedModules = append(aggregatedResult.ScannedModules, result.SkillName)
// If we found a skill, we typically don't scan subdirectories of a skill
// (nested skills are rare/discouraged), but to be safe we can continue or skip.
// Let's SkipDir to avoid scanning internal directories of a skill as potential skills.
return filepath.SkipDir
}
}
return nil
})
}
if foundSkills == 0 {
fmt.Printf("No skills found in %s (checked recursively).\n", rootDir)
} else {
fmt.Printf("\nScanned %d skills.\n", foundSkills)
if outputFile != "" {
handleReport(aggregatedResult, outputFile)
}
}
if issuesFound {
fmt.Println(color.RedString("\nCritical issues found in one or more skills."))
os.Exit(1)
}
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/cmd_test.go | Go | package cmd
import (
"bytes"
"testing"
)
func TestRootCommand(t *testing.T) {
// Reset args before test
rootCmd.SetArgs([]string{"--help"})
var buf bytes.Buffer
rootCmd.SetOut(&buf)
rootCmd.SetErr(&buf)
err := rootCmd.Execute()
if err != nil {
t.Errorf("root command failed: %v", err)
}
output := buf.String()
if output == "" {
t.Error("expected help output, got empty string")
}
// Verify key sections are present in help
expectedSections := []string{
"skill",
"repo",
"init",
}
for _, section := range expectedSections {
if !bytes.Contains([]byte(output), []byte(section)) {
t.Errorf("expected help to contain '%s'", section)
}
}
}
func TestRootHelpShowsSubcommandDetails(t *testing.T) {
rootCmd.SetArgs([]string{"--help"})
var buf bytes.Buffer
rootCmd.SetOut(&buf)
rootCmd.SetErr(&buf)
err := rootCmd.Execute()
if err != nil {
t.Errorf("root command failed: %v", err)
}
output := buf.String()
// Verify subcommand details section is present
subcommandDetails := []string{
"Skill Commands (ask skill <command>):",
"Repository Commands (ask repo <command>):",
"Supported Agents:",
"search",
"install",
"uninstall",
"Claude",
"Cursor",
"antigravity",
}
for _, detail := range subcommandDetails {
if !bytes.Contains([]byte(output), []byte(detail)) {
t.Errorf("expected help to contain subcommand detail '%s'", detail)
}
}
// Verify subcommand details appear AFTER Flags section
flagsIndex := bytes.Index([]byte(output), []byte("Flags:"))
skillCmdsIndex := bytes.Index([]byte(output), []byte("Skill Commands"))
if flagsIndex == -1 {
t.Error("expected help to contain 'Flags:' section")
}
if skillCmdsIndex == -1 {
t.Error("expected help to contain 'Skill Commands' section")
}
if flagsIndex > skillCmdsIndex {
t.Error("expected 'Skill Commands' to appear AFTER 'Flags:' section")
}
}
func TestSkillCommandHelp(t *testing.T) {
// Create a new root command for testing to avoid state pollution
cmd := rootCmd
cmd.SetArgs([]string{"skill", "--help"})
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
err := cmd.Execute()
if err != nil {
t.Errorf("skill command failed: %v", err)
}
output := buf.String()
if output == "" {
t.Error("expected skill help output, got empty string")
}
// Verify at least some subcommands are listed
// Note: We check for a few key ones rather than all to make test less brittle
expectedCommands := []string{
"search",
"install",
"list",
}
for _, cmd := range expectedCommands {
if !bytes.Contains([]byte(output), []byte(cmd)) {
t.Errorf("expected skill help to contain '%s' command", cmd)
}
}
}
func TestRepoCommandHelp(t *testing.T) {
cmd := rootCmd
cmd.SetArgs([]string{"repo", "--help"})
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
err := cmd.Execute()
if err != nil {
t.Errorf("repo command failed: %v", err)
}
output := buf.String()
if output == "" {
t.Error("expected repo help output, got empty string")
}
// Verify subcommands are listed
expectedCommands := []string{
"add",
"list",
}
for _, cmd := range expectedCommands {
if !bytes.Contains([]byte(output), []byte(cmd)) {
t.Errorf("expected repo help to contain '%s' command", cmd)
}
}
}
func TestInitCommandHelp(t *testing.T) {
cmd := rootCmd
cmd.SetArgs([]string{"init", "--help"})
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
err := cmd.Execute()
if err != nil {
t.Errorf("init command help failed: %v", err)
}
output := buf.String()
if !bytes.Contains([]byte(output), []byte("Initialize")) {
t.Error("expected init help to contain 'Initialize'")
}
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/completion.go | Go | package cmd
import (
"os"
"strings"
"github.com/spf13/cobra"
"github.com/yeasy/ask/internal/cache"
"github.com/yeasy/ask/internal/config"
)
// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Short: "Generate shell completion scripts",
Long: `Generate shell completion scripts for ASK.
To load completions:
Bash:
$ source <(ask completion bash)
# To load completions for each session, execute once:
# Linux:
$ ask completion bash > /etc/bash_completion.d/ask
# macOS:
$ ask completion bash > $(brew --prefix)/etc/bash_completion.d/ask
Zsh:
# If shell completion is not already enabled in your environment,
# you will need to enable it. You can execute the following once:
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
# To load completions for each session, execute once:
$ ask completion zsh > "${fpath[1]}/_ask"
# You will need to start a new shell for this setup to take effect.
Fish:
$ ask completion fish | source
# To load completions for each session, execute once:
$ ask completion fish > ~/.config/fish/completions/ask.fish
PowerShell:
PS> ask completion powershell | Out-String | Invoke-Expression
# To load completions for every new session, run:
PS> ask completion powershell > ask.ps1
# and source this file from your PowerShell profile.
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
_ = cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
_ = cmd.Root().GenZshCompletion(os.Stdout)
case "fish":
_ = cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
_ = cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
}
},
}
func init() {
rootCmd.AddCommand(completionCmd)
}
// completeSkillNames provides completion for skill names from local cache
// Used by: install command
func completeSkillNames(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var suggestions []string
// Try to get skills from local cache
reposCache, err := cache.NewReposCache()
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
// Search all cached repos
skills, err := reposCache.SearchSkills("")
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
toCompleteLower := strings.ToLower(toComplete)
for _, skill := range skills {
if toComplete == "" || strings.HasPrefix(strings.ToLower(skill.Name), toCompleteLower) {
// Add both plain name and repo/name format
suggestions = append(suggestions, skill.Name)
fullName := skill.RepoName + "/" + skill.Name
if toComplete == "" || strings.HasPrefix(strings.ToLower(fullName), toCompleteLower) {
suggestions = append(suggestions, fullName)
}
}
}
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
// completeInstalledSkills provides completion for installed skill names
// Used by: uninstall, info commands
func completeInstalledSkills(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var suggestions []string
// Get installed skills from project config
cfg, err := config.LoadConfig()
if err == nil && cfg != nil {
toCompleteLower := strings.ToLower(toComplete)
for _, skill := range cfg.SkillsInfo {
if toComplete == "" || strings.HasPrefix(strings.ToLower(skill.Name), toCompleteLower) {
suggestions = append(suggestions, skill.Name)
}
}
for _, skill := range cfg.Skills {
if toComplete == "" || strings.HasPrefix(strings.ToLower(skill), toCompleteLower) {
suggestions = append(suggestions, skill)
}
}
}
// Also check global config
globalCfg, err := config.LoadConfigByScope(true)
if err == nil && globalCfg != nil {
toCompleteLower := strings.ToLower(toComplete)
for _, skill := range globalCfg.SkillsInfo {
if toComplete == "" || strings.HasPrefix(strings.ToLower(skill.Name), toCompleteLower) {
suggestions = append(suggestions, skill.Name)
}
}
for _, skill := range globalCfg.Skills {
if toComplete == "" || strings.HasPrefix(strings.ToLower(skill), toCompleteLower) {
suggestions = append(suggestions, skill)
}
}
}
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
// completeAgentNames provides completion for agent names
// Used by: install, uninstall, list --agent flag
func completeAgentNames(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
agents := config.GetSupportedAgentNames()
var suggestions []string
toCompleteLower := strings.ToLower(toComplete)
for _, agent := range agents {
if toComplete == "" || strings.HasPrefix(strings.ToLower(agent), toCompleteLower) {
suggestions = append(suggestions, agent)
}
}
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
// completeRepoNames provides completion for repository names
// Used by: repo sync command
func completeRepoNames(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var suggestions []string
cfg, err := config.LoadConfig()
if err != nil {
def := config.DefaultConfig()
cfg = &def
}
toCompleteLower := strings.ToLower(toComplete)
for _, repo := range cfg.Repos {
if toComplete == "" || strings.HasPrefix(strings.ToLower(repo.Name), toCompleteLower) {
suggestions = append(suggestions, repo.Name)
}
}
return suggestions, cobra.ShellCompDirectiveNoFileComp
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/create.go | Go | package cmd
import (
"fmt"
"os"
"regexp"
"github.com/spf13/cobra"
"github.com/yeasy/ask/internal/skill"
)
// createCmd represents the create command
var createCmd = &cobra.Command{
Use: "create <name>",
Short: "Create a new skill from a template",
Long: `Create a new skill directory with a standardized structure.
This will generate a SKILL.md and necessary subdirectories (scripts, references, assets).`,
Args: cobra.ExactArgs(1),
Run: func(_ *cobra.Command, args []string) {
name := args[0]
// Validate name (alphanumeric and dashes only)
match, _ := regexp.MatchString("^[a-zA-Z0-9-]+$", name)
if !match {
fmt.Println("Error: Skill name must contain only alphanumeric characters and dashes.")
os.Exit(1)
}
cwd, err := os.Getwd()
if err != nil {
fmt.Printf("Error getting current working directory: %v\n", err)
os.Exit(1)
}
fmt.Printf("Creating skill '%s'...\n", name)
if err := skill.CreateSkillTemplate(name, cwd); err != nil {
fmt.Printf("Error creating skill: %v\n", err)
os.Exit(1)
}
fmt.Printf("\nSuccessfully created skill '%s'!\n", name)
fmt.Println("\nDirectory structure:")
fmt.Printf(" %s/\n", name)
fmt.Println(" ├── SKILL.md")
fmt.Println(" ├── scripts/")
fmt.Println(" ├── references/")
fmt.Println(" └── assets/")
fmt.Println("\nNext steps:")
fmt.Printf("1. cd %s\n", name)
fmt.Println("2. Edit SKILL.md to describe your skill")
fmt.Println("3. Add scripts to the 'scripts' directory")
},
}
func init() {
skillCmd.AddCommand(createCmd)
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/doctor.go | Go | package cmd
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/yeasy/ask/internal/cache"
"github.com/yeasy/ask/internal/config"
"github.com/yeasy/ask/internal/skill"
)
// DoctorResult represents the result of a health check
type DoctorResult struct {
Category string `json:"category"`
Status string `json:"status"` // "ok", "warning", "error"
Message string `json:"message"`
Details []string `json:"details,omitempty"`
Children []CheckItem `json:"children,omitempty"`
}
// CheckItem represents a single check result
type CheckItem struct {
Name string `json:"name"`
Status string `json:"status"` // "ok", "warning", "error"
Message string `json:"message"`
}
// DoctorReport represents the complete health check report
type DoctorReport struct {
Version string `json:"version"`
Results []DoctorResult `json:"results"`
Summary DoctorSummary `json:"summary"`
}
// DoctorSummary provides overall statistics
type DoctorSummary struct {
TotalChecks int `json:"total_checks"`
PassedChecks int `json:"passed_checks"`
WarningChecks int `json:"warning_checks"`
FailedChecks int `json:"failed_checks"`
}
// doctorCmd represents the doctor command
var doctorCmd = &cobra.Command{
Use: "doctor",
Short: "Diagnose and report on ASK health",
Long: `Run health checks on your ASK installation and project configuration.
This command validates:
- Configuration files (ask.yaml, ask.lock)
- Skills directories and installed skills
- Repository cache status
- System dependencies (git)
- Agent directory detection`,
Example: ` ask doctor # Run all health checks
ask doctor --json # Output results in JSON format`,
Run: runDoctor,
}
var doctorJSON bool
func init() {
rootCmd.AddCommand(doctorCmd)
doctorCmd.Flags().BoolVar(&doctorJSON, "json", false, "output results in JSON format")
}
func runDoctor(_ *cobra.Command, _ []string) {
report := DoctorReport{
Version: "1.0",
Results: []DoctorResult{},
}
// Run all checks
report.Results = append(report.Results, checkConfiguration())
report.Results = append(report.Results, checkSkillsDirectory())
report.Results = append(report.Results, checkRepositoryCache())
report.Results = append(report.Results, checkSystem())
report.Results = append(report.Results, checkAgentDirectories())
// Calculate summary
for _, result := range report.Results {
for _, child := range result.Children {
report.Summary.TotalChecks++
switch child.Status {
case "ok":
report.Summary.PassedChecks++
case "warning":
report.Summary.WarningChecks++
case "error":
report.Summary.FailedChecks++
}
}
}
if doctorJSON {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
_ = encoder.Encode(report)
return
}
// Text output
printDoctorReport(report)
}
func printDoctorReport(report DoctorReport) {
fmt.Println("ASK Doctor - Health Check")
fmt.Println(strings.Repeat("─", 40))
fmt.Println()
for _, result := range report.Results {
statusIcon := getStatusIcon(result.Status)
fmt.Printf("%s %s\n", statusIcon, result.Category)
for _, child := range result.Children {
childIcon := getStatusIcon(child.Status)
fmt.Printf(" %s %s\n", childIcon, child.Message)
}
fmt.Println()
}
// Summary
fmt.Println(strings.Repeat("─", 40))
fmt.Printf("Summary: %d passed", report.Summary.PassedChecks)
if report.Summary.WarningChecks > 0 {
fmt.Printf(", %d warnings", report.Summary.WarningChecks)
}
if report.Summary.FailedChecks > 0 {
fmt.Printf(", %d errors", report.Summary.FailedChecks)
}
fmt.Println()
if report.Summary.FailedChecks > 0 {
os.Exit(1)
}
}
func getStatusIcon(status string) string {
switch status {
case "ok":
return "✓"
case "warning":
return "⚠"
case "error":
return "✗"
default:
return "?"
}
}
func checkConfiguration() DoctorResult {
result := DoctorResult{
Category: "Configuration",
Status: "ok",
Children: []CheckItem{},
}
// Check ask.yaml
if _, err := os.Stat("ask.yaml"); err == nil {
cfg, err := config.LoadConfig()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "ask.yaml",
Status: "error",
Message: fmt.Sprintf("ask.yaml found but invalid: %v", err),
})
result.Status = "error"
} else {
result.Children = append(result.Children, CheckItem{
Name: "ask.yaml",
Status: "ok",
Message: fmt.Sprintf("ask.yaml found (version: %s)", cfg.Version),
})
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "ask.yaml",
Status: "warning",
Message: "ask.yaml not found - run 'ask init' to create",
})
if result.Status == "ok" {
result.Status = "warning"
}
}
// Check ask.lock
if _, err := os.Stat("ask.lock"); err == nil {
lockFile, err := config.LoadLockFile()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "ask.lock",
Status: "warning",
Message: fmt.Sprintf("ask.lock found but invalid: %v", err),
})
if result.Status == "ok" {
result.Status = "warning"
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "ask.lock",
Status: "ok",
Message: fmt.Sprintf("ask.lock found (%d entries)", len(lockFile.Skills)),
})
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "ask.lock",
Status: "ok",
Message: "ask.lock not found (will be created on first install)",
})
}
return result
}
func checkSkillsDirectory() DoctorResult {
result := DoctorResult{
Category: "Skills Directory",
Status: "ok",
Children: []CheckItem{},
}
skillsDir := config.DefaultSkillsDir
if _, err := os.Stat(skillsDir); err == nil {
entries, err := os.ReadDir(skillsDir)
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "directory",
Status: "error",
Message: fmt.Sprintf("Cannot read %s: %v", skillsDir, err),
})
result.Status = "error"
return result
}
// Count skills and check for SKILL.md
var skillCount int
var missingSkillMD []string
for _, entry := range entries {
if entry.IsDir() {
skillCount++
skillPath := filepath.Join(skillsDir, entry.Name())
if !skill.FindSkillMD(skillPath) {
missingSkillMD = append(missingSkillMD, entry.Name())
}
}
}
result.Children = append(result.Children, CheckItem{
Name: "directory",
Status: "ok",
Message: fmt.Sprintf("%s exists (%d skills installed)", skillsDir, skillCount),
})
if len(missingSkillMD) > 0 {
result.Children = append(result.Children, CheckItem{
Name: "skill_md",
Status: "warning",
Message: fmt.Sprintf("%d skills missing SKILL.md: %s", len(missingSkillMD), strings.Join(missingSkillMD, ", ")),
})
if result.Status == "ok" {
result.Status = "warning"
}
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "directory",
Status: "ok",
Message: fmt.Sprintf("%s not found (will be created on first install)", skillsDir),
})
}
return result
}
func checkRepositoryCache() DoctorResult {
result := DoctorResult{
Category: "Repository Cache",
Status: "ok",
Children: []CheckItem{},
}
reposCacheDir := cache.GetReposCacheDir()
if _, err := os.Stat(reposCacheDir); err == nil {
reposCache, err := cache.NewReposCache()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "cache",
Status: "error",
Message: fmt.Sprintf("Cannot access repos cache: %v", err),
})
result.Status = "error"
return result
}
repos := reposCache.GetCachedRepos()
result.Children = append(result.Children, CheckItem{
Name: "cache",
Status: "ok",
Message: fmt.Sprintf("%s exists (%d repos cached)", reposCacheDir, len(repos)),
})
if len(repos) == 0 {
result.Children = append(result.Children, CheckItem{
Name: "sync",
Status: "warning",
Message: "No repos synced - run 'ask repo sync' for faster searches",
})
if result.Status == "ok" {
result.Status = "warning"
}
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "cache",
Status: "ok",
Message: fmt.Sprintf("%s not found (run 'ask repo sync' to populate)", reposCacheDir),
})
}
return result
}
func checkSystem() DoctorResult {
result := DoctorResult{
Category: "System",
Status: "ok",
Children: []CheckItem{},
}
// Check git
gitCmd := exec.Command("git", "--version")
output, err := gitCmd.Output()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "git",
Status: "error",
Message: "git not found - required for cloning skills",
})
result.Status = "error"
} else {
version := strings.TrimSpace(string(output))
result.Children = append(result.Children, CheckItem{
Name: "git",
Status: "ok",
Message: version,
})
}
// Check home directory
home, err := os.UserHomeDir()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "home",
Status: "error",
Message: "Cannot determine home directory",
})
result.Status = "error"
} else {
globalDir := filepath.Join(home, config.GlobalConfigDirName)
if _, err := os.Stat(globalDir); err == nil {
result.Children = append(result.Children, CheckItem{
Name: "global_dir",
Status: "ok",
Message: fmt.Sprintf("Global config: %s", globalDir),
})
} else {
result.Children = append(result.Children, CheckItem{
Name: "global_dir",
Status: "ok",
Message: fmt.Sprintf("Global config: %s (will be created)", globalDir),
})
}
}
return result
}
func checkAgentDirectories() DoctorResult {
result := DoctorResult{
Category: "Agent Directories",
Status: "ok",
Children: []CheckItem{},
}
cwd, err := os.Getwd()
if err != nil {
result.Children = append(result.Children, CheckItem{
Name: "cwd",
Status: "error",
Message: "Cannot get current directory",
})
result.Status = "error"
return result
}
detected := config.DetectExistingToolDirs(cwd)
if len(detected) > 0 {
for _, t := range detected {
result.Children = append(result.Children, CheckItem{
Name: t.Name,
Status: "ok",
Message: fmt.Sprintf("%s detected (%s)", t.Name, t.SkillsDir),
})
}
} else {
result.Children = append(result.Children, CheckItem{
Name: "none",
Status: "ok",
Message: "No agent-specific directories detected (using .agent/skills)",
})
}
return result
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/doctor_test.go | Go | package cmd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDoctorCommand(t *testing.T) {
// Test that doctor command is registered
cmd := doctorCmd
assert.Equal(t, "doctor", cmd.Use)
assert.NotEmpty(t, cmd.Short)
assert.NotEmpty(t, cmd.Long)
}
func TestDoctorFlags(t *testing.T) {
// Test --json flag exists
flag := doctorCmd.Flags().Lookup("json")
assert.NotNil(t, flag, "doctor command should have --json flag")
assert.Equal(t, "false", flag.DefValue)
}
func TestGetStatusIcon(t *testing.T) {
tests := []struct {
status string
expected string
}{
{"ok", "✓"},
{"warning", "⚠"},
{"error", "✗"},
{"unknown", "?"},
}
for _, tt := range tests {
t.Run(tt.status, func(t *testing.T) {
result := getStatusIcon(tt.status)
assert.Equal(t, tt.expected, result)
})
}
}
func TestCheckConfiguration(t *testing.T) {
// Test that checkConfiguration returns a valid result
result := checkConfiguration()
assert.Equal(t, "Configuration", result.Category)
assert.NotEmpty(t, result.Status)
// Should have at least ask.yaml and ask.lock checks
assert.GreaterOrEqual(t, len(result.Children), 1)
}
func TestCheckSystem(t *testing.T) {
// Test that checkSystem returns a valid result
result := checkSystem()
assert.Equal(t, "System", result.Category)
assert.NotEmpty(t, result.Status)
// Should have git check at minimum
assert.GreaterOrEqual(t, len(result.Children), 1)
}
func TestCheckSkillsDirectory(t *testing.T) {
// Test that checkSkillsDirectory returns a valid result
result := checkSkillsDirectory()
assert.Equal(t, "Skills Directory", result.Category)
assert.NotEmpty(t, result.Status)
}
func TestCheckRepositoryCache(t *testing.T) {
// Test that checkRepositoryCache returns a valid result
result := checkRepositoryCache()
assert.Equal(t, "Repository Cache", result.Category)
assert.NotEmpty(t, result.Status)
}
func TestCheckAgentDirectories(t *testing.T) {
// Test that checkAgentDirectories returns a valid result
result := checkAgentDirectories()
assert.Equal(t, "Agent Directories", result.Category)
assert.NotEmpty(t, result.Status)
}
func TestDoctorReportStructure(t *testing.T) {
// Test DoctorReport structure
report := DoctorReport{
Version: "1.0",
Results: []DoctorResult{
{
Category: "Test",
Status: "ok",
Children: []CheckItem{
{Name: "item1", Status: "ok", Message: "test"},
},
},
},
Summary: DoctorSummary{
TotalChecks: 1,
PassedChecks: 1,
WarningChecks: 0,
FailedChecks: 0,
},
}
assert.Equal(t, "1.0", report.Version)
assert.Len(t, report.Results, 1)
assert.Equal(t, 1, report.Summary.TotalChecks)
assert.Equal(t, 1, report.Summary.PassedChecks)
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang | |
cmd/gui.go | Go | package cmd
import (
"log"
"github.com/spf13/cobra"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/yeasy/ask/internal/app"
"github.com/yeasy/ask/internal/server"
"github.com/yeasy/ask/internal/server/web"
)
var guiCmd = &cobra.Command{
Use: "gui",
Short: "Launch the ask desktop interface",
Long: "Launch the ask desktop interface in a native window.",
Run: func(_ *cobra.Command, _ []string) {
startGUI()
},
}
func init() {
rootCmd.AddCommand(guiCmd)
}
// ExecuteGUI starts the GUI application
func ExecuteGUI() {
startGUI()
}
func startGUI() {
// Create an instance of the app structure
app := app.NewApp()
// Create and configure server for API handling (port 0 as we only use the handler)
srv := server.New(0, Version)
// Create application with options
err := wails.Run(&options.App{
Title: "Ask",
Width: 1024,
Height: 768,
AssetServer: &assetserver.Options{
Assets: web.Assets,
Handler: srv.Handler(),
},
BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
OnStartup: app.Startup,
Bind: []interface{}{
app,
},
})
if err != nil {
log.Fatal("Error starting application: " + err.Error())
}
}
| yeasy/ask | 11 | The most powerful Package Manager for Agents Skills: search, query and install/uninstall in seconds! | HTML | yeasy | Baohua Yang |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.