Build secure, scalable content platforms with Revolutionary Moments, Smart Categories, and seamless Stripe integration. From personal blogs to enterprise content hubs, from secure E2EE publishing to real-time P2P content sharing.
allgram Blogs provides enterprise-level security, GDPR compliance, and seamless integration with popular platforms. Perfect for content creators, businesses, and organizations requiring professional content management solutions.
Auto-expiring content, FOMO effect
Virtual folders, intelligent filtering
Seamless monetization, subscriptions
Build robust content platforms with Node.js and Express.js. Our comprehensive API provides blog creation, content management, and enterprise-grade security features. Perfect for building scalable backend services and content management applications.
function greet(user) {
const message = `Hello, ${user.name || 'Guest'}!`;
const log = () => {
console.log("Greeting sent to: " + user.email);
console.log('Data:', {
time: new Date().toISOString(),
status: '✅',
meta: {
permissions: ['read', 'write', "delete"],
verified: true,
},
});
};
return {
message,
send: () => {
alert(message);
log();
},
};
}
const user = {
name: 'Alice',
email: 'alice@example.com',
};
greet(user).send();
Our Node.js integration provides enterprise-grade content management capabilities with minimal setup. Built on proven technologies like Express.js and WebSocket, it offers exceptional performance and reliability for production applications.
Build native iOS content applications with Swift and SwiftUI. Our iOS SDK provides seamless integration with UIKit and SwiftUI, content creation, and secure E2EE implementation. Perfect for creating professional iOS content applications with modern design patterns.
// allgram Blogs Swift iOS Integration Example
import SwiftUI
import Combine
import CryptoKit
// MARK: - Blog Models
struct Blog: Codable, Identifiable {
let id: String
let name: String
let description: String
let isPublic: Bool
let isPaid: Bool
let monthlyPrice: Double?
let participants: [String]
let creationDate: Date
let momentsCount: Int
let subscribersCount: Int
enum CodingKeys: String, CodingKey {
case id = "blog_id"
case name = "blog_name"
case description = "blog_description"
case isPublic = "is_public"
case isPaid = "is_paid"
case monthlyPrice = "monthly_price"
case participants
case creationDate = "creation_datetime"
case momentsCount = "moments_count"
case subscribersCount = "subscribers_count"
}
}
struct Post: Codable, Identifiable {
let id: String
let blogId: String
let author: String
let content: PostContent
let timestamp: Date
let isMoment: Bool
let expirationDate: Date?
let viewsCount: Int
let reactionsCount: Int
let commentsCount: Int
enum CodingKeys: String, CodingKey {
case id = "post_id"
case blogId = "blog"
case author
case content
case timestamp = "creation_datetime"
case isMoment = "is_moment"
case expirationDate = "expiration_date"
case viewsCount = "views_count"
case reactionsCount = "reactions_num"
case commentsCount = "comments_num"
}
}
struct PostContent: Codable {
let text: String?
let media: [String]?
let tags: [String]?
}
// MARK: - Blog Service
class allgramBlogsService: ObservableObject {
@Published var blogs: [Blog] = []
@Published var currentBlog: Blog?
@Published var posts: [Post] = []
@Published var isConnected = false
private var webSocket: URLSessionWebSocketTask?
private var cancellables = Set<AnyCancellable>()
private let baseURL = "https://api.allgram.best"
private let apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
setupWebSocket()
}
// MARK: - WebSocket Setup
private func setupWebSocket() {
guard let url = URL(string: "wss://api.allgram.best/ws/blogs/") else { return }
let session = URLSession(configuration: .default)
webSocket = session.webSocketTask(with: url)
webSocket?.resume()
// Authenticate
let authMessage = WebSocketMessage(type: "auth", apiKey: apiKey)
sendWebSocketMessage(authMessage)
// Start receiving messages
receiveMessage()
}
// MARK: - Blog Management
func createBlog(name: String, description: String, isPublic: Bool = true, isPaid: Bool = false, monthlyPrice: Double? = nil) async throws -> Blog {
let url = URL(string: "\(baseURL)/blogs/create")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let blogData = [
"blog_name": name,
"blog_description": description,
"is_public": isPublic,
"is_paid": isPaid,
"monthly_price": monthlyPrice
]
request.httpBody = try JSONSerialization.data(withJSONObject: blogData)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw BlogError.serverError
}
let blog = try JSONDecoder().decode(Blog.self, from: data)
DispatchQueue.main.async {
self.blogs.append(blog)
}
return blog
}
// MARK: - Post Management
func createPost(blogId: String, content: String, isMoment: Bool = false, expirationDate: Date? = nil) async throws {
let url = URL(string: "\(baseURL)/posts/create")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
var postData: [String: Any] = [
"blog": blogId,
"content": content,
"is_moment": isMoment
]
if let expirationDate = expirationDate {
postData["expiration_date"] = expirationDate.timeIntervalSince1970
}
request.httpBody = try JSONSerialization.data(withJSONObject: postData)
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw BlogError.serverError
}
print("✅ Post created successfully")
}
// MARK: - Moment Creation
func createMoment(blogId: String, content: String, hoursToExpire: Int = 24) async throws {
let expirationDate = Date().addingTimeInterval(TimeInterval(hoursToExpire * 3600))
try await createPost(blogId: blogId, content: content, isMoment: true, expirationDate: expirationDate)
}
// MARK: - WebSocket Communication
private func sendWebSocketMessage(_ message: WebSocketMessage) {
guard let data = try? JSONEncoder().encode(message),
let jsonString = String(data: data, encoding: .utf8) else { return }
let wsMessage = URLSessionWebSocketTask.Message.string(jsonString)
webSocket?.send(wsMessage) { error in
if let error = error {
print("❌ Failed to send WebSocket message: \(error)")
}
}
}
private func receiveMessage() {
webSocket?.receive { [weak self] result in
switch result {
case .success(let message):
self?.handleWebSocketMessage(message)
self?.receiveMessage() // Continue receiving
case .failure(let error):
print("❌ WebSocket receive error: \(error)")
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self?.reconnect()
}
}
}
}
private func handleWebSocketMessage(_ message: URLSessionWebSocketTask.Message) {
switch message {
case .string(let text):
guard let data = text.data(using: .utf8),
let wsMessage = try? JSONDecoder().decode(WebSocketMessage.self, from: data) else { return }
DispatchQueue.main.async {
self.processWebSocketMessage(wsMessage)
}
default:
break
}
}
private func processWebSocketMessage(_ message: WebSocketMessage) {
if let newPosts = message.newPosts {
print("📝 New posts available: \(newPosts)")
handleNewPosts()
} else if let newMoments = message.newMoments {
print("⚡ New moments available: \(newMoments)")
handleNewMoments()
}
}
private func handleNewPosts() {
// Refresh blog posts
if let currentBlog = currentBlog {
loadBlogPosts(blogId: currentBlog.id)
}
}
private func handleNewMoments() {
// Refresh moments
loadMoments()
}
// MARK: - Data Loading
private func loadBlogPosts(blogId: String) {
// Implementation for loading blog posts
// This would typically involve API calls to fetch post history
}
private func loadMoments() {
// Implementation for loading moments
// This would typically involve API calls to fetch moments
}
// MARK: - Utility Methods
private func reconnect() {
print("🔄 Attempting to reconnect...")
setupWebSocket()
}
}
// MARK: - WebSocket Message Model
struct WebSocketMessage: Codable {
let type: String?
let apiKey: String?
let newPosts: Int?
let newMoments: Int?
enum CodingKeys: String, CodingKey {
case type
case apiKey = "api_key"
case newPosts = "new_posts"
case newMoments = "new_moments"
}
}
// MARK: - Error Handling
enum BlogError: Error, LocalizedError {
case serverError
case networkError
case authenticationError
var errorDescription: String? {
switch self {
case .serverError:
return "Server error occurred"
case .networkError:
return "Network connection failed"
case .authenticationError:
return "Authentication failed"
}
}
}
// MARK: - SwiftUI Views
struct BlogListView: View {
@StateObject private var blogService = allgramBlogsService(apiKey: "your-api-key")
var body: some View {
NavigationView {
List(blogService.blogs) { blog in
NavigationLink(destination: BlogDetailView(blog: blog, blogService: blogService)) {
BlogRowView(blog: blog)
}
}
.navigationTitle("Blogs")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("New Blog") {
// Show new blog creation
}
}
}
}
}
}
struct BlogRowView: View {
let blog: Blog
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(blog.name)
.font(.headline)
Spacer()
if blog.isPaid {
Image(systemName: "dollarsign.circle.fill")
.foregroundColor(.green)
}
}
Text(blog.description)
.font(.subheadline)
.foregroundColor(.secondary)
HStack {
Text("\(blog.subscribersCount) subscribers")
.font(.caption)
.foregroundColor(.secondary)
Spacer()
Text("\(blog.momentsCount) moments")
.font(.caption)
.foregroundColor(.secondary)
}
}
.padding(.vertical, 4)
}
}
Our Swift SDK leverages the latest iOS technologies including SwiftUI, Combine, and async/await. Built with modern iOS development patterns, it provides a seamless developer experience while maintaining high performance and security standards.
Build powerful Android content applications with Kotlin and Jetpack Compose. Our Android SDK provides seamless integration with modern Android development tools, content management, and P2P content capabilities. Perfect for creating professional Android content applications.
// allgram Blogs Kotlin Android Integration Example
package com.allgram.blogs
import android.util.Log
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
// MARK: - Data Models
data class Blog(
val blogId: String,
val blogName: String,
val blogDescription: String,
val isPublic: Boolean,
val isPaid: Boolean,
val monthlyPrice: Double?,
val participants: List<String>,
val creationDatetime: Long,
val momentsCount: Int,
val subscribersCount: Int
)
data class Post(
val postId: String,
val blogId: String,
val author: String,
val content: PostContent,
val creationDatetime: Long,
val isMoment: Boolean = false,
val expirationDate: Long? = null,
val viewsCount: Int = 0,
val reactionsCount: Int = 0,
val commentsCount: Int = 0
)
data class PostContent(
val text: String? = null,
val media: List<String>? = null,
val tags: List<String>? = null
)
// MARK: - Blog Service
class allgramBlogsService(
private val apiKey: String,
private val baseUrl: String = "https://api.allgram.best"
) {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
private var webSocket: WebSocket? = null
private val postCallbacks = mutableListOf<(Post) -> Unit>()
private val momentCallbacks = mutableListOf<(Post) -> Unit>()
// MARK: - WebSocket Management
fun connectWebSocket() {
val request = Request.Builder()
.url("wss://api.allgram.best/ws/blogs/")
.build()
webSocket = client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
Log.d("allgramBlogs", "✅ WebSocket connected")
// Authenticate
sendWebSocketMessage(JSONObject().apply {
put("type", "auth")
put("api_key", apiKey)
}.toString())
}
override fun onMessage(webSocket: WebSocket, text: String) {
try {
val json = JSONObject(text)
handleWebSocketMessage(json)
} catch (e: Exception) {
Log.e("allgramBlogs", "Failed to parse WebSocket message", e)
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Log.e("allgramBlogs", "WebSocket failure", t)
// Attempt reconnection
CoroutineScope(Dispatchers.IO).launch {
delay(5000)
connectWebSocket()
}
}
})
}
// MARK: - Blog Management
suspend fun createBlog(
name: String,
description: String,
isPublic: Boolean = true,
isPaid: Boolean = false,
monthlyPrice: Double? = null
): Result<Blog> = withContext(Dispatchers.IO) {
try {
val requestBody = JSONObject().apply {
put("blog_name", name)
put("blog_description", description)
put("is_public", isPublic)
put("is_paid", isPaid)
if (monthlyPrice != null) {
put("monthly_price", monthlyPrice)
}
}.toString()
val request = Request.Builder()
.url("$baseUrl/blogs/create")
.post(requestBody.toRequestBody("application/json".toMediaType()))
.addHeader("Authorization", "Bearer $apiKey")
.build()
val response = client.newCall(request).execute()
if (response.isSuccessful) {
val responseBody = response.body?.string()
val blogJson = JSONObject(responseBody ?: "")
val blog = Blog(
blogId = blogJson.getString("blog_id"),
blogName = blogJson.getString("blog_name"),
blogDescription = blogJson.getString("blog_description"),
isPublic = blogJson.optBoolean("is_public", true),
isPaid = blogJson.optBoolean("is_paid", false),
monthlyPrice = if (blogJson.has("monthly_price")) blogJson.optDouble("monthly_price") else null,
participants = emptyList(),
creationDatetime = blogJson.optLong("creation_datetime", System.currentTimeMillis() / 1000),
momentsCount = blogJson.optInt("moments_count", 0),
subscribersCount = blogJson.optInt("subscribers_count", 0)
)
Log.d("allgramBlogs", "✅ Blog created: ${blog.blogName}")
Result.success(blog)
} else {
Log.e("allgramBlogs", "Failed to create blog: ${response.code}")
Result.failure(Exception("Server error: ${response.code}"))
}
} catch (e: Exception) {
Log.e("allgramBlogs", "Exception creating blog", e)
Result.failure(e)
}
}
// MARK: - Post Management
suspend fun createPost(
blogId: String,
content: String,
isMoment: Boolean = false,
expirationDate: Long? = null
): Result<Unit> = withContext(Dispatchers.IO) {
try {
val postData = JSONObject().apply {
put("blog", blogId)
put("content", content)
put("is_moment", isMoment)
if (expirationDate != null) {
put("expiration_date", expirationDate)
}
}
val request = Request.Builder()
.url("$baseUrl/posts/create")
.post(postData.toString().toRequestBody("application/json".toMediaType()))
.addHeader("Authorization", "Bearer $apiKey")
.build()
val response = client.newCall(request).execute()
if (response.isSuccessful) {
Log.d("allgramBlogs", "✅ Post created successfully")
Result.success(Unit)
} else {
Log.e("allgramBlogs", "Failed to create post: ${response.code}")
Result.failure(Exception("Server error: ${response.code}"))
}
} catch (e: Exception) {
Log.e("allgramBlogs", "Exception creating post", e)
Result.failure(e)
}
}
// MARK: - Moment Creation
suspend fun createMoment(
blogId: String,
content: String,
hoursToExpire: Int = 24
): Result<Unit> = withContext(Dispatchers.IO) {
val expirationDate = System.currentTimeMillis() / 1000 + (hoursToExpire * 3600)
return createPost(blogId, content, true, expirationDate)
}
// MARK: - WebSocket Communication
private fun sendWebSocketMessage(message: String) {
webSocket?.send(message) ?: run {
Log.w("allgramBlogs", "WebSocket not connected")
}
}
private fun handleWebSocketMessage(json: JSONObject) {
when {
json.has("new_posts") -> {
val newPosts = json.getInt("new_posts")
Log.d("allgramBlogs", "📝 New posts available: $newPosts")
handleNewPosts()
}
json.has("new_moments") -> {
val newMoments = json.getInt("new_moments")
Log.d("allgramBlogs", "⚡ New moments available: $newMoments")
handleNewMoments()
}
}
}
private fun handleNewPosts() {
Log.d("allgramBlogs", "📝 New posts available")
// Notify callbacks
postCallbacks.forEach { callback ->
// This would typically involve fetching new posts
}
}
private fun handleNewMoments() {
Log.d("allgramBlogs", "⚡ New moments available")
// Notify callbacks
momentCallbacks.forEach { callback ->
// This would typically involve fetching new moments
}
}
// MARK: - Callbacks
fun addPostCallback(callback: (Post) -> Unit) {
postCallbacks.add(callback)
}
fun addMomentCallback(callback: (Post) -> Unit) {
momentCallbacks.add(callback)
}
fun removePostCallback(callback: (Post) -> Unit) {
postCallbacks.remove(callback)
}
fun removeMomentCallback(callback: (Post) -> Unit) {
momentCallbacks.remove(callback)
}
// MARK: - Cleanup
fun disconnect() {
webSocket?.close(1000, "Disconnecting")
webSocket = null
}
}
// MARK: - ViewModel
class BlogsViewModel(
private val blogService: allgramBlogsService
) : ViewModel() {
private val _blogs = MutableStateFlow<List<Blog>>(emptyList())
val blogs: StateFlow<List<Blog>> = _blogs.asStateFlow()
private val _currentBlog = MutableStateFlow<Blog?>(null)
val currentBlog: StateFlow<Blog?> = _currentBlog.asStateFlow()
private val _posts = MutableStateFlow<List<Post>>(emptyList())
val posts: StateFlow<List<Post>> = _posts.asStateFlow()
private val _isLoading = MutableStateFlow(false)
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
init {
setupBlogService()
}
private fun setupBlogService() {
blogService.addPostCallback { post ->
if (post.blogId == _currentBlog.value?.blogId) {
_posts.value = _posts.value + post
}
}
blogService.addMomentCallback { moment ->
// Handle new moments
Log.d("BlogsViewModel", "New moment received: ${moment.postId}")
}
}
fun createBlog(name: String, description: String, isPublic: Boolean = true, isPaid: Boolean = false) {
viewModelScope.launch {
_isLoading.value = true
try {
val result = blogService.createBlog(name, description, isPublic, isPaid)
result.onSuccess { blog ->
_blogs.value = _blogs.value + blog
}.onFailure { error ->
Log.e("BlogsViewModel", "Failed to create blog", error)
}
} finally {
_isLoading.value = false
}
}
}
fun createPost(content: String) {
val currentBlog = _currentBlog.value ?: return
viewModelScope.launch {
val result = blogService.createPost(currentBlog.blogId, content)
result.onFailure { error ->
Log.e("BlogsViewModel", "Failed to create post", error)
}
}
}
fun createMoment(content: String, hoursToExpire: Int = 24) {
val currentBlog = _currentBlog.value ?: return
viewModelScope.launch {
val result = blogService.createMoment(currentBlog.blogId, content, hoursToExpire)
result.onFailure { error ->
Log.e("BlogsViewModel", "Failed to create moment", error)
}
}
}
fun selectBlog(blog: Blog) {
_currentBlog.value = blog
// Load blog posts
loadBlogPosts(blog.blogId)
}
private fun loadBlogPosts(blogId: String) {
// Implementation for loading blog posts
// This would typically involve API calls to fetch post history
}
override fun onCleared() {
super.onCleared()
blogService.disconnect()
}
}
// MARK: - Compose UI
@Composable
fun BlogListScreen(
viewModel: BlogsViewModel = viewModel { BlogsViewModel(allgramBlogsService("your-api-key")) }
) {
val blogs by viewModel.blogs.collectAsState()
val isLoading by viewModel.isLoading.collectAsState()
LazyColumn {
items(blogs) { blog ->
BlogItem(
blog = blog,
onClick = { viewModel.selectBlog(blog) }
)
}
}
if (isLoading) {
CircularProgressIndicator()
}
}
@Composable
fun BlogItem(
blog: Blog,
onClick: () -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.clickable { onClick() },
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = blog.blogName,
style = MaterialTheme.typography.h6
)
if (blog.isPaid) {
Icon(
imageVector = Icons.Default.AttachMoney,
contentDescription = "Paid Blog",
tint = Color.Green
)
}
}
Text(
text = blog.blogDescription,
style = MaterialTheme.typography.body2,
color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
)
HStack {
Text(
text = "${blog.subscribersCount} subscribers",
style = MaterialTheme.typography.caption,
color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
)
Spacer()
Text(
text = "${blog.momentsCount} moments",
style = MaterialTheme.typography.caption,
color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
)
}
}
}
}
Our Kotlin SDK leverages the latest Android technologies including Jetpack Compose, Coroutines, and modern Android architecture patterns. Built with performance and developer experience in mind, it provides a robust foundation for building scalable content applications.
Ready to take your content platform to the next level? Explore our comprehensive resources and advanced features to build enterprise-grade content applications with allgram.
Learn about our enterprise security features, GDPR compliance, and FIPS 140-2 certification.
Learn More →Discover advanced techniques for optimizing content performance and scalability.
Learn More →Join our developer community for support, updates, and collaboration.
Join Community →