Skip to content

YemenKidsStudioSuite #436

Backlog
Backlog

Description

@Naderalwedad

#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="${1:-YemenKidsStudioSuite}"
ANDROID_DIR="$ROOT_DIR/android"
SERVER_DIR="$ROOT_DIR/server"
PACKAGE_NAME="com.yemenkids.studio"
PACKAGE_PATH="com/yemenkids/studio"
DEFAULT_API_URL="${API_BASE_URL:-http://10.0.2.2:8080/}"

gradle_escape() {
local value="$1"
value=${value//\/\\}
value=${value//"/\"}
printf '%s' "$value"
}

API_URL_ESCAPED="$(gradle_escape "$DEFAULT_API_URL")"

printf '=== [1/7] إنشاء هيكل المشروع ===\n'
mkdir -p
"$ANDROID_DIR/app/src/main/java/$PACKAGE_PATH/core/security"
"$ANDROID_DIR/app/src/main/java/$PACKAGE_PATH/core/network"
"$ANDROID_DIR/app/src/main/java/$PACKAGE_PATH/data/remote"
"$ANDROID_DIR/app/src/main/java/$PACKAGE_PATH/data/repository"
"$ANDROID_DIR/app/src/main/java/$PACKAGE_PATH/ui/admin"
"$ANDROID_DIR/app/src/main/res/values"
"$ANDROID_DIR/app/src/debug"
"$SERVER_DIR/src"

printf '=== [2/7] إعداد Gradle وأندرويد ===\n'
cat <<'EOF' > "$ANDROID_DIR/settings.gradle.kts"
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}

rootProject.name = "YemenKidsStudio"
include(":app")
EOF

cat <<'EOF' > "$ANDROID_DIR/build.gradle.kts"
plugins {
id("com.android.application") version "8.7.3" apply false
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
}
EOF

cat <<'EOF' > "$ANDROID_DIR/gradle.properties"
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
EOF

cat < "$ANDROID_DIR/app/build.gradle.kts"
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
id("org.jetbrains.kotlin.plugin.serialization")
}

android {
namespace = "$PACKAGE_NAME"
compileSdk = 35

defaultConfig {
    applicationId = "$PACKAGE_NAME"
    minSdk = 26
    targetSdk = 35
    versionCode = 3
    versionName = "1.2.0"
    buildConfigField("String", "API_BASE_URL", "\"$API_URL_ESCAPED\"")
}

buildTypes {
    debug {
        isMinifyEnabled = false
    }
    release {
        isMinifyEnabled = true
        isShrinkResources = true
        proguardFiles(
            getDefaultProguardFile("proguard-android-optimize.txt"),
            "proguard-rules.pro"
        )
    }
}

compileOptions {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

kotlinOptions {
    jvmTarget = "17"
}

buildFeatures {
    compose = true
    buildConfig = true
}

}

dependencies {
implementation(platform("androidx.compose:compose-bom:2025.02.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-extended")
implementation("androidx.activity:activity-compose:1.10.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("androidx.security:security-crypto:1.1.0-alpha06")

}
EOF

touch "$ANDROID_DIR/app/proguard-rules.pro"

printf '=== [3/7] إعداد Manifest والأمان والشبكة ===\n'
cat <<'EOF' > "$ANDROID_DIR/app/src/main/AndroidManifest.xml"

EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/debug/AndroidManifest.xml"

EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/main/res/values/strings.xml"

Yemen Kids Studio EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/main/java/com/yemenkids/studio/core/security/TokenStore.kt"
package com.yemenkids.studio.core.security

import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey

class TokenStore(context: Context) {
private val masterKey = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()

private val prefs = EncryptedSharedPreferences.create(
    context,
    "yemen_kids_secure_prefs",
    masterKey,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)

fun saveAccessToken(token: String) {
    prefs.edit().putString(KEY_ACCESS_TOKEN, token).apply()
}

fun getAccessToken(): String? = prefs.getString(KEY_ACCESS_TOKEN, null)

fun clearToken() {
    prefs.edit().remove(KEY_ACCESS_TOKEN).apply()
}

private companion object {
    const val KEY_ACCESS_TOKEN = "admin_access_token"
}

}
EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/main/java/com/yemenkids/studio/data/remote/YemenKidsApiService.kt"
package com.yemenkids.studio.data.remote

import kotlinx.serialization.Serializable
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.POST
import retrofit2.http.Path

@serializable
data class CreateJobRequest(
val promptText: String,
val audienceType: String = "GENERAL",
val durationSec: Int,
val aspectRatio: String,
val autoPublish: Boolean,
val publishMode: String,
val scheduledAtUtc: String? = null,
val targetPlatforms: List,
val madeForKids: Boolean = false,
val notifyEmail: Boolean = true
)

@serializable
data class PlatformStatusDto(
val platform: String,
val status: String,
val postUrl: String? = null,
val errorMessage: String? = null
)

@serializable
data class JobStatusResponse(
val jobId: String,
val pipelineStage: String,
val audienceType: String = "GENERAL",
val durationSec: Int = 180,
val awaitingApproval: Boolean = false,
val previewUrl: String? = null,
val emailReportSent: Boolean = false,
val emailReportError: String? = null,
val platforms: List = emptyList()
)

interface YemenKidsApiService {
@post("api/v1/yemen-kids/jobs")
suspend fun createJob(
@Header("Idempotency-Key") idempotencyKey: String,
@Body request: CreateJobRequest
): JobStatusResponse

@GET("api/v1/yemen-kids/jobs/{jobId}")
suspend fun getJobStatus(@Path("jobId") jobId: String): JobStatusResponse

@POST("api/v1/yemen-kids/jobs/{jobId}/approve")
suspend fun approveJob(@Path("jobId") jobId: String): JobStatusResponse

@POST("api/v1/yemen-kids/jobs/{jobId}/retry/{platform}")
suspend fun retryPlatform(
    @Path("jobId") jobId: String,
    @Path("platform") platform: String
): JobStatusResponse

}
EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/main/java/com/yemenkids/studio/core/network/NetworkModule.kt"
package com.yemenkids.studio.core.network

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import com.yemenkids.studio.BuildConfig
import com.yemenkids.studio.core.security.TokenStore
import com.yemenkids.studio.data.remote.YemenKidsApiService
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

class AuthInterceptor(private val tokenStore: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain) = chain.proceed(
chain.request().newBuilder().apply {
tokenStore.getAccessToken()?.takeIf { it.isNotBlank() }?.let { token ->
header("Authorization", "Bearer $token")
}
header("Accept", "application/json")
}.build()
)
}

object NetworkModule {
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}

fun provideApiService(tokenStore: TokenStore): YemenKidsApiService {
    val logging = HttpLoggingInterceptor().apply {
        redactHeader("Authorization")
        level = if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor.Level.BASIC
        } else {
            HttpLoggingInterceptor.Level.NONE
        }
    }

    val client = OkHttpClient.Builder()
        .addInterceptor(AuthInterceptor(tokenStore))
        .addInterceptor(logging)
        .connectTimeout(20, TimeUnit.SECONDS)
        .readTimeout(35, TimeUnit.SECONDS)
        .writeTimeout(35, TimeUnit.SECONDS)
        .build()

    return Retrofit.Builder()
        .baseUrl(BuildConfig.API_BASE_URL)
        .client(client)
        .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
        .build()
        .create(YemenKidsApiService::class.java)
}

}
EOF

printf '=== [4/7] إنشاء Repository و ViewModel ===\n'
cat <<'EOF' > "$ANDROID_DIR/app/src/main/java/com/yemenkids/studio/data/repository/YemenKidsRepository.kt"
package com.yemenkids.studio.data.repository

import com.yemenkids.studio.data.remote.CreateJobRequest
import com.yemenkids.studio.data.remote.JobStatusResponse
import com.yemenkids.studio.data.remote.YemenKidsApiService
import retrofit2.HttpException
import java.io.IOException
import java.util.UUID

sealed interface ApiResult {
data class Success(val data: T) : ApiResult
data class Error(
val message: String,
val isNetworkError: Boolean = false,
val isUnauthorized: Boolean = false
) : ApiResult
}

interface YemenKidsRepository {
suspend fun submitDailyJob(
request: CreateJobRequest,
idempotencyKey: String = UUID.randomUUID().toString()
): ApiResult
suspend fun fetchJobStatus(jobId: String): ApiResult
suspend fun approveJob(jobId: String): ApiResult
suspend fun retryPlatform(jobId: String, platform: String): ApiResult
}

class YemenKidsRepositoryImpl(
private val apiService: YemenKidsApiService
) : YemenKidsRepository {
override suspend fun submitDailyJob(
request: CreateJobRequest,
idempotencyKey: String
) = safeApiCall {
apiService.createJob(idempotencyKey = idempotencyKey, request = request)
}

override suspend fun fetchJobStatus(jobId: String) = safeApiCall {
    apiService.getJobStatus(jobId)
}

override suspend fun approveJob(jobId: String) = safeApiCall {
    apiService.approveJob(jobId)
}

override suspend fun retryPlatform(jobId: String, platform: String) = safeApiCall {
    apiService.retryPlatform(jobId, platform)
}

private suspend fun <T> safeApiCall(block: suspend () -> T): ApiResult<T> = try {
    ApiResult.Success(block())
} catch (_: IOException) {
    ApiResult.Error("تعذر الاتصال بالخادم. تحقق من الشبكة وعنوان API.", isNetworkError = true)
} catch (e: HttpException) {
    when (e.code()) {
        401 -> ApiResult.Error("رمز المصادقة غير صالح أو منتهٍ. حدّث الرمز.", isUnauthorized = true)
        404 -> ApiResult.Error("المهمة المطلوبة غير موجودة.")
        429 -> ApiResult.Error("تم تجاوز حد الطلبات. أعد المحاولة لاحقاً.")
        else -> ApiResult.Error("فشل طلب الخادم (HTTP ${e.code()}).")
    }
} catch (e: Exception) {
    ApiResult.Error(e.localizedMessage ?: "حدث خطأ غير متوقع.")
}

}
EOF

cat <<'EOF' > "$ANDROID_DIR/app/src/main/java/com/yemenkids/studio/ui/admin/YemenKidsAdminViewModel.kt"
package com.yemenkids.studio.ui.admin

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.yemenkids.studio.core.security.TokenStore
import com.yemenkids.studio.data.remote.CreateJobRequest
import com.yemenkids.studio.data.remote.JobStatusResponse
import com.yemenkids.studio.data.repository.ApiResult
import com.yemenkids.studio.data.repository.YemenKidsRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.UUID

private const val REPORT_EMAIL = "World1kids1@gmail.com"

enum class PublishMode { IMMEDIATE, SCHEDULED }
enum class AudienceType(val arLabel: String) {
GENERAL("محتوى عام / عائلي"),
KIDS("مخصص للأطفال")
}
enum class PlatformStatusLabel(val arText: String) {
QUEUED("في الانتظار"),
UPLOADING("جاري الرفع"),
PUBLISHED("منشور"),
REVIEW("بانتظار المراجعة"),
FAILED("فشل")
}

data class DurationOption(val seconds: Int, val label: String)
val DEFAULT_DURATION_OPTIONS = listOf(
DurationOption(45, "45 ثانية"),
DurationOption(60, "دقيقة"),
DurationOption(180, "3 دقائق"),
DurationOption(300, "5 دقائق"),
DurationOption(600, "10 دقائق")
)

data class PlatformPublishState(
val name: String,
val selected: Boolean,
val status: PlatformStatusLabel,
val detail: String
)

data class YemenKidsUiState(
val hasAuthToken: Boolean = false,
val tokenInput: String = "",
val showTokenDialog: Boolean = false,
val promptText: String = "",
val audienceType: AudienceType = AudienceType.GENERAL,
val durationSec: Int = 180,
val aspectRatio: String = "16:9",
val autoPublish: Boolean = true,
val publishMode: PublishMode = PublishMode.IMMEDIATE,
val scheduleText: String = "",
val pipelineStage: String = "جاهز لاستقبال المهمة",
val awaitingApproval: Boolean = false,
val isApproving: Boolean = false,
val previewUrl: String? = null,
val emailReportStatus: String = "سيتم إرسال التقرير إلى $REPORT_EMAIL عند اكتمال المهمة",
val isSubmitting: Boolean = false,
val errorBanner: String? = null,
val jobId: String? = null,
val platforms: List = listOf(
PlatformPublishState("YouTube", true, PlatformStatusLabel.QUEUED, "لم يبدأ التنفيذ"),
PlatformPublishState("TikTok", true, PlatformStatusLabel.QUEUED, "لم يبدأ التنفيذ"),
PlatformPublishState("Facebook", true, PlatformStatusLabel.QUEUED, "لم يبدأ التنفيذ"),
PlatformPublishState("Instagram", true, PlatformStatusLabel.QUEUED, "لم يبدأ التنفيذ")
)
)

class YemenKidsAdminViewModel(
private val repository: YemenKidsRepository,
private val tokenStore: TokenStore
) : ViewModel() {
private val _uiState = MutableStateFlow(
YemenKidsUiState(hasAuthToken = !tokenStore.getAccessToken().isNullOrBlank())
)
val uiState: StateFlow = _uiState.asStateFlow()

private var currentJobId: String? = null
private var pendingIdempotencyKey: String? = null
private var pollingJob: Job? = null

fun openTokenDialog() {
    _uiState.update { it.copy(tokenInput = tokenStore.getAccessToken().orEmpty(), showTokenDialog = true) }
}
fun closeTokenDialog() = _uiState.update { it.copy(showTokenDialog = false) }
fun onTokenInputChange(value: String) = _uiState.update { it.copy(tokenInput = value) }
fun saveToken() {
    val token = _uiState.value.tokenInput.trim()
    if (token.isEmpty()) return
    tokenStore.saveAccessToken(token)
    _uiState.update { it.copy(hasAuthToken = true, showTokenDialog = false, errorBanner = null) }
}
fun clearToken() {
    tokenStore.clearToken()
    _uiState.update { it.copy(hasAuthToken = false, tokenInput = "", showTokenDialog = false) }
}
fun onPromptChange(value: String) = _uiState.update { it.copy(promptText = value) }
fun onAudienceTypeChange(type: AudienceType) = _uiState.update { it.copy(audienceType = type) }
fun onDurationChange(seconds: Int) = _uiState.update {
    it.copy(durationSec = seconds, aspectRatio = if (seconds >= 180) "16:9" else "9:16")
}
fun onAspectRatioChange(value: String) = _uiState.update { it.copy(aspectRatio = value) }
fun onAutoPublishChange(value: Boolean) = _uiState.update { it.copy(autoPublish = value) }
fun onPublishModeChange(value: PublishMode) = _uiState.update { it.copy(publishMode = value) }
fun onScheduleChange(value: String) = _uiState.update { it.copy(scheduleText = value) }
fun clearErrorBanner() = _uiState.update { it.copy(errorBanner = null) }
fun onTogglePlatform(name: String) = _uiState.update { state ->
    state.copy(platforms = state.platforms.map { if (it.name == name) it.copy(selected = !it.selected) else it })
}

fun submitJob() {
    val state = _uiState.value
    val platforms = state.platforms.filter { it.selected }.map { it.name.uppercase() }
    if (state.isSubmitting) return
    if (state.promptText.isBlank()) {
        _uiState.update { it.copy(errorBanner = "اكتب وصف الفيديو أولاً.") }
        return
    }
    if (platforms.isEmpty()) {
        _uiState.update { it.copy(errorBanner = "اختر منصة واحدة على الأقل.") }
        return
    }
    if (!state.hasAuthToken) {
        _uiState.update { it.copy(errorBanner = "أدخل رمز المصادقة أولاً.", showTokenDialog = true) }
        return
    }
    if (state.publishMode == PublishMode.SCHEDULED && state.scheduleText.isBlank()) {
        _uiState.update { it.copy(errorBanner = "أدخل موعد النشر بصيغة ISO-8601 مع المنطقة الزمنية.") }
        return
    }

    val key = pendingIdempotencyKey ?: UUID.randomUUID().toString().also { pendingIdempotencyKey = it }
    val request = CreateJobRequest(
        promptText = state.promptText.trim(),
        audienceType = state.audienceType.name,
        durationSec = state.durationSec,
        aspectRatio = state.aspectRatio,
        autoPublish = state.autoPublish,
        publishMode = state.publishMode.name,
        scheduledAtUtc = if (state.publishMode == PublishMode.SCHEDULED) state.scheduleText.trim() else null,
        targetPlatforms = platforms,
        madeForKids = state.audienceType == AudienceType.KIDS,
        notifyEmail = true
    )

    viewModelScope.launch {
        _uiState.update { it.copy(isSubmitting = true, errorBanner = null, pipelineStage = "جاري إرسال المهمة إلى الخادم...") }
        when (val result = repository.submitDailyJob(request, key)) {
            is ApiResult.Success -> {
                pendingIdempotencyKey = null
                currentJobId = result.data.jobId
                applyJobStatus(result.data)
                _uiState.update { it.copy(isSubmitting = false) }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions