Psyter Media Upload API - Detailed Structure

Project: Psyter Media Upload API
Technology: ASP.NET Web API 2 (.NET Framework 4.7.2)
Purpose: Dedicated media file upload and management service
Authentication: OAuth 2.0 (Bearer Token)
Last Updated: November 5, 2025


๐Ÿ“ Root Structure

Media/
โ”œโ”€โ”€ PsyterMediaUploadAPI/          # Main API project
โ”‚   โ”œโ”€โ”€ App_Start/                 # Application startup
โ”‚   โ”œโ”€โ”€ Controllers/               # API controllers
โ”‚   โ”œโ”€โ”€ Models/                    # Data models
โ”‚   โ”œโ”€โ”€ Repository/                # Data access layer
โ”‚   โ”œโ”€โ”€ Providers/                 # OAuth providers
โ”‚   โ”œโ”€โ”€ Helper/                    # Utility helpers
โ”‚   โ”œโ”€โ”€ Media/                     # Uploaded media storage
โ”‚   โ”œโ”€โ”€ Content/                   # Static content
โ”‚   โ”œโ”€โ”€ bin/                       # Compiled binaries
โ”‚   โ”œโ”€โ”€ obj/                       # Build objects
โ”‚   โ”œโ”€โ”€ Properties/                # Assembly info
โ”‚   โ”œโ”€โ”€ Global.asax                # Application entry
โ”‚   โ”œโ”€โ”€ Web.config                 # Configuration
โ”‚   โ”œโ”€โ”€ packages.config            # NuGet packages
โ”‚   โ””โ”€โ”€ PsyterMediaUploadAPI.csproj # Project file
โ”œโ”€โ”€ packages/                      # NuGet packages cache
โ”œโ”€โ”€ PsyterMediaUploadAPI.sln       # Solution file
โ””โ”€โ”€ azure-pipelines.yml            # CI/CD pipeline

๐ŸŽฏ Project Overview

Purpose

Dedicated media file upload service separate from main API for:
- Performance: Offload file processing from main API
- Scalability: Independent scaling for media operations
- Storage Management: Centralized media storage
- Security: Isolated validation and processing
- Optimization: Specialized for large file uploads

Key Features

โœ… Multi-format Support: Images, videos, documents, audio
โœ… Large File Handling: Up to 100 MB per file
โœ… Security Validation: File type, size, MIME type verification
โœ… Organized Storage: User-based folder structure
โœ… Multiple Categories: Profile images, documents, homework, agreements
โœ… PDF Generation: Create agreement PDFs with signatures
โœ… Database Integration: Track uploaded files metadata
โœ… OAuth Authentication: Secure access control


โš™๏ธ Configuration

Web.config Settings

Key Configurations:

<appSettings>
    <add key="commandTimeout" value="600"/>
    <add key="MaxFileSize" value="104857600"/> <!-- 100 MB -->
</appSettings>

Connection String:
- PsyterDatabase: Same as main API (encrypted)
- Shares user authentication and file metadata storage

File Upload Limits:

<!-- ASP.NET -->
<httpRuntime maxRequestLength="104857600" /> <!-- 100 MB -->

<!-- IIS -->
<requestLimits maxAllowedContentLength="104857600" />

Machine Key:
- Same as main API for token validation
- Enables cross-API authentication


๐Ÿ“ฆ Dependencies

Core Framework

  • ASP.NET Web API: 5.2.7
  • ASP.NET MVC: 5.2.3
  • .NET Framework: 4.7.2

Authentication

  • Microsoft.Owin: 3.1.0
  • Microsoft.Owin.Security.OAuth: 3.1.0

Data & Serialization

  • Newtonsoft.Json: 11.0.0
  • System.Data.SqlClient: Built-in

Document Processing

  • iTextSharp: 5.5.13.3 (PDF generation)

Utilities

  • System.IO: File operations
  • System.Net.Http: Multipart form data

๐ŸŽฎ Controllers

MediaController.cs

File: Controllers/MediaController.cs
Route Prefix: /Media
Lines of Code: ~700

Purpose: Handle all media file uploads and management


๐Ÿ“ค Upload Endpoints

POST /Media/UploadMedia

Purpose: Upload media files to server

Authorization: Required (Bearer token)

Content-Type: multipart/form-data

Form Parameters:

{
    UploadCategory: string,    // MediaCategory enum value
    UserType: string,          // E_UserType enum value
    UserId: string,            // User ID
    HomeWorkId: string?,       // Required for homework uploads
    UserFullName: string?,     // Required for agreement uploads
    Culture: string?,          // Language for agreement PDF
    Files: File[]              // Uploaded files
}

Media Categories:

  1. ProfileImage
    - Path: /Media/[UserType]/User_[UserId]/ProfileImage/
    - Formats: PNG, JPG, JPEG
    - Max Files: 1
    - Max Size: 100 MB
    - Use: User profile photos

  2. EducationHistory
    - Path: /Media/[UserType]/User_[UserId]/EducationHistory/
    - Formats: DOC, DOCX, XLSX, PDF, JPG, JPEG, PNG
    - Max Files: 3
    - Use: Educational certificates, diplomas

  3. SCRC
    - Path: /Media/[UserType]/User_[UserId]/SCRC/
    - Formats: PNG, JPG, JPEG, PDF
    - Max Files: Multiple
    - Use: Saudi Commission for Health Specialties (SCRC) certificates

  4. ShortBio
    - Path: /Media/[UserType]/User_[UserId]/ShortBio/
    - Formats: MP4
    - Max Files: 1
    - Use: Provider introduction video

  5. PaymentAttachment
    - Path: /Media/[UserType]/User_[UserId]/PaymentAttachment/
    - Formats: DOC, DOCX, XLSX, PDF, JPG, JPEG, PNG
    - Max Files: 1
    - Use: Payment receipts, invoices

  6. HomeWork
    - Path: /Media/CareProvider/User_[UserId]/HomeWork/HomeWork_[HomeWorkId]/
    - Formats: DOC, DOCX, XLSX, PDF, JPG, JPEG, PNG, TXT
    - Max Files: Multiple
    - Use: Homework assignment files from provider

  7. HomeWorkSubmission
    - Path: /Media/Client/User_[UserId]/HomeWorkSubmission/HomeWork_[HomeWorkId]/
    - Formats: DOC, DOCX, XLSX, PDF, JPG, JPEG, PNG, TXT
    - Max Files: Multiple
    - Use: Homework submission files from client

  8. ArticleImages
    - Path: /Media/ArticleImages/
    - Formats: PNG, JPG, JPEG
    - Max Files: Multiple
    - Use: Blog article images

  9. AgreementAcceptance
    - Path: /Media/CareProvider/User_[UserId]/AgreementAcceptance/
    - Formats: PNG, JPG, JPEG (signature image)
    - Max Files: 1
    - Use: Provider agreement signature
    - Special: Generates PDF agreement automatically

  10. BookingInvoices

    • Path: /Media/BookingInvoices/
    • Formats: PDF only
    • Max Files: 1
    • Use: Appointment booking invoices
  11. NationalID

    • Path: /Media/[UserType]/User_[UserId]/NationalID/
    • Formats: PNG, JPG, JPEG
    • Max Files: Multiple
    • Use: Government-issued ID verification

Upload Process:

  1. Validate Request:
    - Check required parameters
    - Validate user authorization
    - Verify MIME type is multipart

  2. File Validations:
    - File count limits per category
    - File size (max 100 MB)
    - File extension validation
    - MIME type validation (base64 signature check)

  3. Determine Storage Path:
    - Get physical path from database config
    - Build user-specific directory structure
    - Create directories if not exist

  4. Upload Files:
    - Stream files to disk
    - Generate unique filenames (GUID)
    - Preserve original extensions

  5. Post-Processing:
    - For Homework: Save file metadata to database
    - For Agreement: Generate PDF with signature
    - Return file URLs

Response:

{
    "Status": 1,
    "Reason": "SUCCESS",
    "Message": "Success",
    "Data": [
        {
            "FileName": "ProfileImage_abc123.jpg",
            "FilePath": "/Media/CareProvider/User_123/ProfileImage/ProfileImage_abc123.jpg",
            "FileType": ".jpg",
            "HomeWorkType": null
        }
    ]
}

Error Responses:

  • INVALID_PARAMETERS: Missing required parameters
  • PHYSICAL_DIRECTORY_NOT_FOUND: Storage path not configured
  • INVALID_MIME_TYPE: Not multipart/form-data
  • CANT_UPLOAD_MORE_THAN_ONE_FILE: Exceeded file count limit
  • CANT_UPLOAD_MORE_THAN_3_FILES: For education history
  • FILE_SIZE_IS_LARGER_THAN_ALLOWED: File > 100 MB
  • FILE_EXTENSION_NOT_ALLOWED: Invalid file extension
  • FILE_MIMETYPE_NOT_ALLOWED: MIME type mismatch

๐Ÿ—‘๏ธ Delete Endpoints

POST /Media/DeleteMediaFile

Purpose: Delete uploaded media file

Authorization: Required

Request:

{
    "MediaId": 123,
    "UserId": 456,
    "MediaCategory": 6
}

Process:
1. Validate request parameters
2. Check user authorization
3. Query database for file path
4. Delete physical file from disk
5. Delete metadata from database

Response:

{
    "Status": 1,
    "Reason": "SUCCESS",
    "Message": "File deleted successfully"
}

Supported Categories:
- HomeWork
- HomeWorkSubmission
- (Other categories can be added)


๐Ÿ“„ PDF Generation Endpoints

POST /Media/RegenrateAgreement

Purpose: Regenerate provider agreement PDF

Authorization: Required

Request:

{
    "UserLoginInfoId": 123,
    "FullName": "Dr. John Smith",
    "SignatureMediaPath": "/Media/CareProvider/User_123/AgreementAcceptance/signature.png"
}

Process:
1. Validate parameters
2. Build storage path
3. Call iTextSharpHelper to create PDF
4. Embed signature image
5. Return PDF file path

Response:

{
    "Status": 1,
    "Data": {
        "FileName": "Agreement_123.pdf",
        "FilePath": "/Media/CareProvider/User_123/AgreementAcceptance/Agreement_123.pdf",
        "FileType": ".pdf"
    }
}

Agreement PDF Contents:
- Platform terms and conditions
- Provider responsibilities
- Privacy policy
- Payment terms
- User signature
- Timestamp


๐Ÿ”’ Security Features

File Validation

Multi-Layer Security:

  1. Extension Validation:

    AllowedExtensions = ".doc,.docx,.xlsx,.pdf,.jpg,.jpeg,.png"
    

  2. MIME Type Validation:
    - Checks Content-Type header
    - Cross-validates with file extension

  3. Base64 Signature Validation:
    - Reads file header bytes
    - Validates against known file signatures
    - Prevents extension spoofing

Example Signatures:

"IVBO" โ†’ PNG
"/9J/" โ†’ JPEG/JPG
"JVBE" โ†’ PDF
"AAAA" โ†’ MP4
"UESD" โ†’ DOCX/XLSX
"0M8R" โ†’ DOC/XLS

  1. Size Validation:
    - Maximum 100 MB per file
    - Configurable via Web.config

  2. Count Validation:
    - Category-specific limits
    - Prevents abuse

Authorization

OAuth 2.0:
- Bearer token required
- Token validated against main API
- User can only upload to own folders
- Admin can upload to any category

Path Security

Secure Path Construction:
- No user input in path building
- All paths validated
- Directory traversal prevented
- Only configured base paths used


๐Ÿ“‚ Storage Structure

Physical Directory Layout

Media/
โ”œโ”€โ”€ CareProvider/
โ”‚   โ””โ”€โ”€ User_[ProviderId]/
โ”‚       โ”œโ”€โ”€ ProfileImage/
โ”‚       โ”‚   โ””โ”€โ”€ ProfileImage_[GUID].jpg
โ”‚       โ”œโ”€โ”€ EducationHistory/
โ”‚       โ”‚   โ”œโ”€โ”€ EducationHistory_[GUID].pdf
โ”‚       โ”‚   โ””โ”€โ”€ EducationHistory_[GUID].jpg
โ”‚       โ”œโ”€โ”€ SCRC/
โ”‚       โ”‚   โ””โ”€โ”€ SCRC_[GUID].pdf
โ”‚       โ”œโ”€โ”€ ShortBio/
โ”‚       โ”‚   โ””โ”€โ”€ ShortBio_[GUID].mp4
โ”‚       โ”œโ”€โ”€ HomeWork/
โ”‚       โ”‚   โ””โ”€โ”€ HomeWork_[HomeWorkId]/
โ”‚       โ”‚       โ”œโ”€โ”€ HomeWork_[GUID].pdf
โ”‚       โ”‚       โ””โ”€โ”€ HomeWork_[GUID].jpg
โ”‚       โ”œโ”€โ”€ AgreementAcceptance/
โ”‚       โ”‚   โ”œโ”€โ”€ AgreementAcceptance_[GUID].png
โ”‚       โ”‚   โ””โ”€โ”€ Agreement_[UserId].pdf
โ”‚       โ””โ”€โ”€ NationalID/
โ”‚           โ””โ”€โ”€ NationalID_[GUID].jpg
โ”œโ”€โ”€ Client/
โ”‚   โ””โ”€โ”€ User_[ClientId]/
โ”‚       โ”œโ”€โ”€ ProfileImage/
โ”‚       โ”œโ”€โ”€ PaymentAttachment/
โ”‚       โ”œโ”€โ”€ HomeWorkSubmission/
โ”‚       โ”‚   โ””โ”€โ”€ HomeWork_[HomeWorkId]/
โ”‚       โ”‚       โ””โ”€โ”€ HomeWorkSubmission_[GUID].pdf
โ”‚       โ””โ”€โ”€ NationalID/
โ”œโ”€โ”€ ArticleImages/
โ”‚   โ””โ”€โ”€ ArticleImages_[GUID].jpg
โ””โ”€โ”€ BookingInvoices/
    โ””โ”€โ”€ BookingInvoices_[GUID].pdf

File Naming Convention

Format: [Category]_[GUID][Extension]

Examples:
- ProfileImage_abc123-def456-789ghi.jpg
- HomeWork_e1f2g3h4-i5j6-k7l8-m9n0-o1p2q3r4s5t6.pdf
- SCRC_x1y2z3a4-b5c6-d7e8-f9g0-h1i2j3k4l5m6.pdf

Benefits:
- Unique filenames (no collisions)
- Organized by category
- Easy to identify file type
- Prevents overwriting


๐Ÿ—„๏ธ Repository Layer

MediaRepository.cs

File: Repository/MediaRepository.cs

Purpose: Database operations for media files

Key Methods:

GetAppConfigSettingsByGroupId

public ApplicationSettingResponse GetAppConfigSettingsByGroupId(int groupId)

Purpose: Get media storage configuration

Stored Procedure: APP_CONFIG_BY_GROUPID

Configuration Groups:
- PsyterMedia (ID: 1)
- PsyterMediaPhysicalPath: Base storage directory

Returns:

{
    "AppConfiguration": [
        {
            "Id": 1,
            "PropertyKey": "PsyterMediaPhysicalPath",
            "PropertyValue": "D:\\MediaStorage\\Psyter\\"
        }
    ],
    "Status": "SUCCESS"
}

SaveHomeWorkImages

public async Task<FileListWrapper> SaveHomeWorkImages(long homeWorkId, string filesDetailXML)

Purpose: Save homework file metadata to database

Stored Procedure: SAVE_HOME_WORK_FILES_DETAIL

Parameters:
- @HomeWorkId: Homework ID
- @xmlData: XML list of files
- @Status: Output parameter

XML Format:

<Files>
    <FileObject>
        <FileName>HomeWork_abc123.pdf</FileName>
        <FilePath>/Media/CareProvider/.../HomeWork_abc123.pdf</FilePath>
        <FileType>.pdf</FileType>
        <HomeWorkType>1</HomeWorkType>
    </FileObject>
</Files>

Returns: List of files with database IDs

DeleteMediaFromDB

public async Task<FileObject> DeleteMediaFromDB(long userId, long mediaId, int category)

Purpose: Delete file record and get file path

Stored Procedure: DELETE_HOME_WORK_FILE

Parameters:
- @UserId: User ID (for authorization)
- @MediaFileId: File ID
- @Category: Media category

Returns: File path for physical deletion


๐Ÿ“ Models

MediaRequest.cs

DeleteMediaRequest:

public class DeleteMediaRequest
{
    [Required]
    public long MediaId { get; set; }

    [Required]
    public long UserId { get; set; }

    [Required]
    public MediaCategory MediaCategory { get; set; }
}

RegenrateAgreementRequest:

public class RegenrateAgreementRequest
{
    [Required]
    public long UserLoginInfoId { get; set; }

    [Required]
    public string FullName { get; set; }

    [Required]
    public string SignatureMediaPath { get; set; }
}

FileObject.cs

public class FileObject
{
    public long? FileId { get; set; }
    public string FileName { get; set; }
    public string FilePath { get; set; }
    public string FileType { get; set; }
    public int? HomeWorkType { get; set; }
    public DateTime? UploadDate { get; set; }
}

CommonObject.cs

public class ApplicationConfiguration
{
    public int Id { get; set; }
    public string PropertyKey { get; set; }
    public string PropertyValue { get; set; }
    public string Description { get; set; }
}

Enums.cs

MediaCategory:

public enum MediaCategory
{
    None = 0,
    ProfileImage = 1,
    EducationHistory = 2,
    SCRC = 3,
    ShortBio = 4,
    PaymentAttachment = 5,
    HomeWork = 6,
    HomeWorkSubmission = 7,
    ActicleImages = 8,
    AgreementAcceptance = 9,
    BookingInvoices = 10,
    NationalID = 11
}

E_UserType:

public enum E_UserType
{
    Client = 1,
    CareProvider = 2,
    Admin = 3
}

E_ResponseReason:

public enum E_ResponseReason
{
    SUCCESS = 0,
    ERROR = 1,
    INVALID_PARAMETERS = 2,
    PHYSICAL_DIRECTORY_NOT_FOUND = 3,
    INVALID_MIME_TYPE = 4,
    FILE_SIZE_IS_LARGER_THAN_ALLOWED = 5,
    FILE_EXTENSION_NOT_ALLOWED = 6,
    FILE_MIMETYPE_NOT_ALLOWED = 7,
    CANT_UPLOAD_MORE_THAN_ONE_FILE = 8,
    CANT_UPLOAD_MORE_THAN_3_FILES = 9,
    CANT_DELETE = 10,
    SQL_SERVER_EXCEPTION = 11
}

E_HomeWorkType:

public enum E_HomeWorkType
{
    HomeWork = 1,
    HomeWorkSubmission = 2
}


๐Ÿ”ง Helper Classes

iTextSharpHelper.cs

File: Helper/iTextSharpHelper.cs

Purpose: PDF generation for agreements

Key Method:

public async Task<FileObject> CreateAgreementPDF(
    string userId, 
    string userName, 
    string relativePath, 
    string signatureImagePath, 
    string language)

Process:
1. Create PDF document
2. Add agreement text (Arabic or English)
3. Embed signature image
4. Add user name and date
5. Add terms and conditions
6. Save to disk
7. Return file info

PDF Contents:
- Platform logo
- Agreement title
- Terms and conditions
- Provider name
- Signature image
- Date and timestamp
- Legal disclaimers

SecurityHelper.cs

File: Helper/SecurityHelper.cs

Purpose: Security utilities (shared with main API)

Key Methods:
- EncryptString() - AES encryption
- DecryptString() - AES decryption
- HashPassword() - Password hashing
- GenerateToken() - Random token generation


๐Ÿš€ Deployment

Azure DevOps Pipeline

File: azure-pipelines.yml

Pipeline Configuration:

trigger: master
pool: 'DevWebServerAgentPool'
buildConfiguration: 'Release'

Steps:
1. NuGet Restore: Restore packages
2. Build: MSBuild release configuration
3. Package: Create deployment package
4. Publish Artifacts: Store build output
5. Deploy: Copy to target directory

Deployment Target:

D:\ROOT\Development\Psyter\Master\MediaAPIs

Manual Deployment

Steps:

  1. Build:

    msbuild PsyterMediaUploadAPI.sln /p:Configuration=Release
    

  2. Configure Storage:
    - Set media physical path in database
    - Create base directory structure
    - Set folder permissions (IIS_IUSRS)

  3. Update Web.config:
    - Switch connection string (dev โ†’ prod)
    - Verify MaxFileSize setting
    - Enable custom errors

  4. Deploy to IIS:
    - Create application pool (.NET 4.7.2)
    - Configure site/application
    - Set authentication (Anonymous + Windows)
    - Test upload endpoint

  5. Verify:
    - Test file upload
    - Check storage paths
    - Verify PDF generation
    - Monitor logs


๐Ÿ“Š Integration with Main API

How Main API Uses Media API

Upload Flow:

  1. Client/Provider App:
    - Select file to upload
    - Choose category (profile, homework, etc.)
    - Call Media API endpoint

  2. Media API:
    - Validate and save file
    - Return file URL

  3. Main API:
    - Receive file URL from client
    - Store URL in database
    - Associate with user profile/homework/etc.

Example - Profile Image Upload:

Mobile App โ†’ Media API (/Media/UploadMedia)
  โ†“ Returns URL
Mobile App โ†’ Main API (/User/UpdateUserProfile)
  โ†“ Saves URL
Database (UserProfile.ProfileImageUrl)

Example - Homework Assignment:

Provider App โ†’ Media API (Upload homework file)
  โ†“ Returns URL
Provider App โ†’ Main API (/HomeWork/SaveHomeWork)
  โ†“ Saves homework with file URLs
Database (HomeWork + HomeWorkFiles tables)

Database Tables

HomeWorkFiles Table:

CREATE TABLE HomeWorkFiles (
    HomeWorkFileId BIGINT PRIMARY KEY IDENTITY,
    HomeWorkId BIGINT NOT NULL,
    FileName NVARCHAR(255),
    FilePath NVARCHAR(500),
    FileType NVARCHAR(10),
    HomeWorkType SMALLINT, -- 1=Assignment, 2=Submission
    UploadDate DATETIME,
    UploadedBy BIGINT
)

UserProfileFiles Table:

CREATE TABLE UserProfileFiles (
    FileId BIGINT PRIMARY KEY IDENTITY,
    UserLoginInfoId BIGINT NOT NULL,
    FileCategory INT, -- Education, SCRC, etc.
    FileName NVARCHAR(255),
    FilePath NVARCHAR(500),
    FileType NVARCHAR(10),
    UploadDate DATETIME
)


๐Ÿ“ˆ Performance Considerations

Optimizations

  1. Streaming Uploads:
    - Files streamed directly to disk
    - No in-memory buffering
    - Supports large files

  2. Async Operations:
    - Async file I/O
    - Async database operations
    - Non-blocking processing

  3. Separate API:
    - Dedicated resources
    - Independent scaling
    - No impact on main API

  4. Storage:
    - Direct file system access
    - No cloud storage overhead
    - Fast local I/O

Scalability

Horizontal Scaling:
- Load balancer in front
- Shared network storage (NAS/SAN)
- Multiple Media API instances

Vertical Scaling:
- Increase IIS connection limits
- Add more CPU/RAM
- Faster storage (SSD)

CDN Integration:
- Serve files via CDN
- Cache static content
- Reduce API load


๐Ÿ” Monitoring & Logging

Exception Handling

Global Exception Handler:
- Catches all unhandled exceptions
- Logs to file/database
- Returns standardized error response

Error Response:

{
    "Status": 0,
    "Reason": "ERROR",
    "Message": "An error occurred during file upload",
    "Data": null
}

Logging

What’s Logged:
- All file uploads (success/failure)
- File deletions
- Validation errors
- Exception stack traces
- User actions

Log Location:
- Same as main API logs
- Separate log file optional


๐Ÿ” Security Best Practices

Implemented Security

โœ… Authentication: OAuth 2.0 bearer token
โœ… Authorization: User can only access own files
โœ… Input Validation: All parameters validated
โœ… File Validation: Multi-layer (extension, MIME, signature)
โœ… Size Limits: 100 MB maximum
โœ… Path Security: No directory traversal
โœ… Secure Storage: User-based folders
โœ… HTTPS: SSL/TLS encryption
โœ… CORS: Restricted origins

Security Recommendations

Production Hardening:
1. Enable custom errors in Web.config
2. Remove server headers
3. Implement rate limiting
4. Add virus scanning integration
5. Set up file retention policies
6. Implement access logs
7. Regular security audits


๐Ÿ“š API Documentation

Endpoint Summary

Total Endpoints: 3

  1. POST /Media/UploadMedia
    - Upload files to server
    - 11 media categories
    - Multi-file support

  2. POST /Media/DeleteMediaFile
    - Delete uploaded file
    - Physical + database deletion

  3. POST /Media/RegenrateAgreement
    - Generate agreement PDF
    - Embed signature image

Request Examples

Upload Profile Image:

POST /Media/UploadMedia HTTP/1.1
Authorization: Bearer {token}
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

------WebKitFormBoundary
Content-Disposition: form-data; name="UploadCategory"

1
------WebKitFormBoundary
Content-Disposition: form-data; name="UserType"

2
------WebKitFormBoundary
Content-Disposition: form-data; name="UserId"

123
------WebKitFormBoundary
Content-Disposition: form-data; name="Files"; filename="profile.jpg"
Content-Type: image/jpeg

[Binary data]
------WebKitFormBoundary--

Delete File:

POST /Media/DeleteMediaFile HTTP/1.1
Authorization: Bearer {token}
Content-Type: application/json

{
    "MediaId": 456,
    "UserId": 123,
    "MediaCategory": 6
}


๐ŸŽฏ Key Features Summary

Core Functionality

โœ… Multi-format file uploads (images, videos, documents)
โœ… Secure file validation (extension, MIME, signature)
โœ… Organized storage structure
โœ… Database metadata tracking
โœ… File deletion support
โœ… PDF generation with signatures
โœ… Large file support (100 MB)
โœ… OAuth 2.0 authentication

Advanced Features

โœ… Homework file management
โœ… Agreement PDF generation
โœ… Base64 signature validation
โœ… Multi-language support (agreements)
โœ… Configurable storage paths
โœ… Category-specific validation rules
โœ… Async file operations


๐Ÿ“Š Technology Stack

Framework: ASP.NET Web API 2
Language: C# (.NET Framework 4.7.2)
Authentication: OAuth 2.0
Database: SQL Server (metadata only)
Storage: File System
PDF: iTextSharp
Deployment: IIS + Azure DevOps


๐Ÿ”„ Typical Upload Flow

Complete File Upload Process

  1. User Action:
    - User selects file in mobile/web app
    - App prepares multipart request
    - App gets auth token from main API

  2. API Request:

    POST /Media/UploadMedia
    Headers: Authorization: Bearer {token}
    Body: multipart/form-data
    

  3. Media API Processing:
    - Validate bearer token
    - Parse form data
    - Validate file (size, extension, MIME)
    - Get storage path from config
    - Create user directory
    - Stream file to disk with GUID filename
    - Save metadata to database (if applicable)
    - Generate PDF (if agreement)

  4. Response:

    {
        "Status": 1,
        "Data": [{
            "FilePath": "/Media/CareProvider/User_123/ProfileImage/ProfileImage_abc.jpg"
        }]
    }
    

  5. App Updates:
    - App receives file URL
    - Calls main API to update user profile
    - Main API saves URL to database

  6. Display:
    - App loads image from URL
    - CDN serves file (if configured)


๐Ÿงช Testing

Test Scenarios

Upload Tests:
- โœ… Valid file upload
- โœ… Invalid file extension
- โœ… File too large
- โœ… MIME type mismatch
- โœ… Multiple files
- โœ… Missing parameters
- โœ… Unauthorized access

Delete Tests:
- โœ… Delete own file
- โœ… Delete non-existent file
- โœ… Delete another user’s file (should fail)
- โœ… Physical file removed
- โœ… Database record removed

PDF Generation Tests:
- โœ… Generate agreement with signature
- โœ… Arabic vs English content
- โœ… Invalid signature path


๐Ÿ“ˆ Usage Statistics

Typical Usage:
- Profile Images: 1-2 per user
- Education Certificates: 2-3 per provider
- Homework Files: 1-5 per assignment
- Homework Submissions: 1-3 per submission
- Agreement PDFs: 1 per provider

Storage Estimates:
- Average profile image: 500 KB
- Average document: 2 MB
- Average video bio: 20 MB
- Average homework file: 1 MB

For 1000 Users:
- Providers: 500 users ร— 50 MB = 25 GB
- Clients: 500 users ร— 5 MB = 2.5 GB
- Total: ~30 GB


๐ŸŽ‰ Benefits of Separate Media API

  1. Performance: Main API not blocked by large uploads
  2. Scalability: Scale media service independently
  3. Specialization: Optimized for file operations
  4. Security: Isolated file validation
  5. Maintenance: Update without affecting main API
  6. Monitoring: Dedicated logs for uploads
  7. Cost: Cheaper storage tier for media server

END OF MEDIA API DOCUMENTATION


Completion Status:
- โœ… Android Client (COMPLETED)
- โœ… AndroidCareProvider (COMPLETED)
- โœ… APIs - Part 1 (COMPLETED)
- โœ… APIs - Part 2 (COMPLETED)
- โœ… Media API (COMPLETED)
- โญ๏ธ NodeServer (NEXT)
- Pending: Tahoon_API, Web, WindowsService, IOSCareProvider