Mark-Lasfar commited on
Commit ·
4dd49ba
1
Parent(s): fe9d07e
Add GraphQL
Browse filesFiles changed (4)
- package-lock.json+155
- package.json+1
- server.js+566-45
- utils/socket-client.jsAdded+32
53 unmodified lines5455565758591659 unmodified lines1719172017211722172317241365 unmodified lines3090309130923093309430953425 unmodified lines652165226523652465256526904 unmodified lines74317432743374347435743640 unmodified lines74777478747974807481748253 unmodified lines"passport-oauth2": "^1.8.0","pdf-parse": "^1.1.4","sharp": "^0.32.6","stripe": "^22.2.2","swagger-jsdoc": "^6.2.8","swagger-ui-express": "^5.0.1",1659 unmodified lines"node": ">=18"}},"node_modules/@tokenizer/inflate": {"version": "0.4.1","resolved": "https://registry.npmmirror.com/@tokenizer/inflate/-/inflate-0.4.1.tgz",1365 unmodified lines"once": "^1.4.0"}},"node_modules/es-define-property": {"version": "1.0.1","resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",3425 unmodified lines"integrity": "sha512-TK5ZA9U5RqCwMpfoMq/l1mrH0JAR7y7KRvOBx0n2869aLxch+gT9GhN3yUfjiw+d/DiF1mKo14+hd62JyMmoBg==","license": "MIT"},"node_modules/sparse-bitfield": {"version": "3.0.3","resolved": "https://registry.npmmirror.com/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",904 unmodified lines"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==","license": "ISC"},"node_modules/xml": {"version": "1.0.1","resolved": "https://registry.npmmirror.com/xml/-/xml-1.0.1.tgz",40 unmodified lines"node": ">=4.0"}},"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmmirror.com/xtend/-/xtend-4.0.2.tgz",53 unmodified lines545556575859601659 unmodified lines1720172117221723172417251726172717281729173017311365 unmodified lines3097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473425 unmodified lines65736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652904 unmodified lines75577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758340 unmodified lines7624762576267627762876297630763176327633763476357636763753 unmodified lines"passport-oauth2": "^1.8.0","pdf-parse": "^1.1.4","sharp": "^0.32.6","socket.io-client": "^4.8.3","stripe": "^22.2.2","swagger-jsdoc": "^6.2.8","swagger-ui-express": "^5.0.1",1659 unmodified lines"node": ">=18"}},"node_modules/@socket.io/component-emitter": {"version": "3.1.2","resolved": "https://registry.npmmirror.com/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz","integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==","license": "MIT"},"node_modules/@tokenizer/inflate": {"version": "0.4.1","resolved": "https://registry.npmmirror.com/@tokenizer/inflate/-/inflate-0.4.1.tgz",1365 unmodified lines"once": "^1.4.0"}},"node_modules/engine.io-client": {"version": "6.6.6","resolved": "https://registry.npmmirror.com/engine.io-client/-/engine.io-client-6.6.6.tgz","integrity": "sha512-iY6QdftLQ9pyiPoX082bpf/u1UewnOaJrtJIF9T0++QB34lZrj0uP+Q/bj8AlUsAxqhnkTV2BS8SBZSxOmoV5Q==","license": "MIT","dependencies": {"@socket.io/component-emitter": "~3.1.0","debug": "~4.4.1","engine.io-parser": "~5.2.1","ws": "~8.21.0","xmlhttprequest-ssl": "~2.1.1"}},"node_modules/engine.io-client/node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==","license": "MIT","dependencies": {"ms": "^2.1.3"},"engines": {"node": ">=6.0"},"peerDependenciesMeta": {"supports-color": {"optional": true}}},"node_modules/engine.io-client/node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},"node_modules/engine.io-parser": {"version": "5.2.3","resolved": "https://registry.npmmirror.com/engine.io-parser/-/engine.io-parser-5.2.3.tgz","integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==","license": "MIT","engines": {"node": ">=10.0.0"}},"node_modules/es-define-property": {"version": "1.0.1","resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",3425 unmodified lines"integrity": "sha512-TK5ZA9U5RqCwMpfoMq/l1mrH0JAR7y7KRvOBx0n2869aLxch+gT9GhN3yUfjiw+d/DiF1mKo14+hd62JyMmoBg==","license": "MIT"},"node_modules/socket.io-client": {"version": "4.8.3","resolved": "https://registry.npmmirror.com/socket.io-client/-/socket.io-client-4.8.3.tgz","integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==","license": "MIT","dependencies": {"@socket.io/component-emitter": "~3.1.0","debug": "~4.4.1","engine.io-client": "~6.6.1","socket.io-parser": "~4.2.4"},"engines": {"node": ">=10.0.0"}},"node_modules/socket.io-client/node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==","license": "MIT","dependencies": {"ms": "^2.1.3"},"engines": {"node": ">=6.0"},"peerDependenciesMeta": {"supports-color": {"optional": true}}},"node_modules/socket.io-client/node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},"node_modules/socket.io-parser": {"version": "4.2.7","resolved": "https://registry.npmmirror.com/socket.io-parser/-/socket.io-parser-4.2.7.tgz","integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==","license": "MIT","dependencies": {"@socket.io/component-emitter": "~3.1.0","debug": "~4.4.1"},"engines": {"node": ">=10.0.0"}},"node_modules/socket.io-parser/node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==","license": "MIT","dependencies": {"ms": "^2.1.3"},"engines": {"node": ">=6.0"},"peerDependenciesMeta": {"supports-color": {"optional": true}}},"node_modules/socket.io-parser/node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},"node_modules/sparse-bitfield": {"version": "3.0.3","resolved": "https://registry.npmmirror.com/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",904 unmodified lines"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==","license": "ISC"},"node_modules/ws": {"version": "8.21.1","resolved": "https://registry.npmmirror.com/ws/-/ws-8.21.1.tgz","integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==","license": "MIT","engines": {"node": ">=10.0.0"},"peerDependencies": {"bufferutil": "^4.0.1","utf-8-validate": ">=5.0.2"},"peerDependenciesMeta": {"bufferutil": {"optional": true},"utf-8-validate": {"optional": true}}},"node_modules/xml": {"version": "1.0.1","resolved": "https://registry.npmmirror.com/xml/-/xml-1.0.1.tgz",40 unmodified lines"node": ">=4.0"}},"node_modules/xmlhttprequest-ssl": {"version": "2.1.2","resolved": "https://registry.npmmirror.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz","integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==","engines": {"node": ">=0.4.0"}},"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmmirror.com/xtend/-/xtend-4.0.2.tgz",
74 unmodified lines75767778798074 unmodified lines"passport-oauth2": "^1.8.0","pdf-parse": "^1.1.4","sharp": "^0.32.6","stripe": "^22.2.2","swagger-jsdoc": "^6.2.8","swagger-ui-express": "^5.0.1",74 unmodified lines7576777879808174 unmodified lines"passport-oauth2": "^1.8.0","pdf-parse": "^1.1.4","sharp": "^0.32.6","socket.io-client": "^4.8.3","stripe": "^22.2.2","swagger-jsdoc": "^6.2.8","swagger-ui-express": "^5.0.1",
75 unmodified lines767778798081295 unmodified lines377378379380381382726 unmodified lines110911101111111211131114111511161117111811191120112111221123112411253222 unmodified lines4348434943504351435243532 unmodified lines4356435743584359436043615922 unmodified lines1028410285102861028710288102891 unmodified line10291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031116 unmodified lines1032810329103301033110332103331033424 unmodified lines103591036010361103621036310364103656 unmodified lines103721037310374103751037610377103781 unmodified line1038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104338081 unmodified lines18515185161851718518185191852018521185221852356 unmodified lines18580185811858218583185841858517464 unmodified lines36050360513605236053360543605575 unmodified linesconst app = express();app.set('trust proxy', true);app.use(cors({295 unmodified lines'/api/subscription/renew','/api/subscription/cancel','/api/users/:userId/badges','/api/users/:userId','/api/admin/stores/:userId/toggle','/api/admin/stores/:userId',726 unmodified lines// ============================================const messageUpload = multer({storage: multer.memoryStorage(),limits: { fileSize: 10 * 1024 * 1024 }, // 10MB for messagesfileFilter: (req, file, cb) => {const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp','application/pdf','audio/mpeg', 'audio/webm', 'audio/mp4', 'audio/ogg'];if (allowedTypes.includes(file.mimetype)) {cb(null, true);} else {cb(new Error('File type not allowed. Allowed: images, PDF, audio files'), false);}}});3222 unmodified linesinteraction: {bronze: { type: Boolean, default: false }, // 10 ردود},unlockedAt: { type: Date, default: null },updatedAt: { type: Date, default: Date.now }},2 unmodified lineslikes: { bronze: false, silver: false, gold: false, red: false },interaction: { bronze: false },unlockedAt: null,updatedAt: Date.now}},5922 unmodified lines}});// ============================================// GET /api/users/:userId/badges - جلب البرونزيات المفتوحة فقط// ============================================1 unmodified linetry {const { userId } = req.params;// ✅ جلب جميع البيانات بشكل متوازيconst [badges, viewCount, likeCount, replyCount] = await Promise.all([getUserBadges(userId),getUniqueViewsCount(userId),getTotalPostLikes(userId),getTotalUserReplies(userId)]);// ✅ حساب التاليlet nextBadge = null;let nextThreshold = null;let progress = 100;let nextBadgeType = null;// ✅ برونزيات المشاهدات (باستخدام البيانات المخزنة)const viewsBadges = badges.views || { unlocked: [], count: 0 };const hasSilver = viewsBadges.unlocked.some(b => b.key === 'silver');const hasGold = viewsBadges.unlocked.some(b => b.key === 'gold');16 unmodified linesnextBadgeType = 'views';}// ✅ برونزيات الإعجاباتconst likesBadges = badges.likes || { unlocked: [], count: 0 };const hasLikesBronze = likesBadges.unlocked.some(b => b.key === 'bronze');const hasLikesRed = likesBadges.unlocked.some(b => b.key === 'red');24 unmodified lines}}// ✅ برونزيات التفاعلconst interactionBadges = badges.interaction || { unlocked: [], count: 0 };const hasInteractionBronze = interactionBadges.unlocked.some(b => b.key === 'bronze');6 unmodified lines}}// ✅ إذا اكتمل كل شيءif (!nextBadge) {nextBadge = 'All badges collected! 🎉';nextThreshold = null;1 unmodified linenextBadgeType = 'complete';}// ✅ حساب نسبة التقدم الإجماليةconst totalBadges = badges.totalCount || 0;const totalPossible = 3 + 4 + 1; // views(3) + likes(4) + interaction(1)const overallProgress = Math.min((totalBadges / totalPossible) * 100, 100);res.json({userId,viewCount,likeCount,replyCount,// ✅ البرونزيات المفتوحة فقطbadges: {views: {unlocked: badges.views?.unlocked || [],count: badges.views?.count || 0},likes: {unlocked: badges.likes?.unlocked || [],count: badges.likes?.count || 0},interaction: {unlocked: badges.interaction?.unlocked || [],count: badges.interaction?.count || 0},unlocked: badges.unlocked || [],totalCount: totalBadges},thresholds: {views: VIEW_BADGE_THRESHOLDS,likes: LIKE_BADGE_THRESHOLDS,interaction: INTERACTION_BADGE_THRESHOLDS},nextBadge,nextThreshold,nextBadgeType,progress: Math.min(Math.round(progress), 100),overallProgress: Math.min(Math.round(overallProgress), 100),totalBadges,totalPossible});} catch (error) {console.error('Error getting badges:', error);res.status(500).json({ error: 'Failed to get badges' });}});// ============================================// GET /api/users/:userId - جلب بيانات مستخدم معين للوسام8081 unmodified linesuploadStream.end(file.buffer);});let attachmentType = 'file';if (file.mimetype.startsWith('image/')) attachmentType = 'image';else if (file.mimetype.startsWith('audio/')) attachmentType = 'audio';attachments.push({type: attachmentType,56 unmodified linesconst populatedMessage = await message.populate('senderId', 'username profile.nickname profile.avatar');res.status(201).json({ success: true, data: populatedMessage });} catch (error) {17464 unmodified lines{ loc: '/feed.html', changefreq: 'daily', priority: 0.9 },{ loc: '/videos.html', changefreq: 'daily', priority: 0.9 },{ loc: '/video.html', changefreq: 'daily', priority: 0.9 },{ loc: '/template-store.html', changefreq: 'daily', priority: 0.9 },{ loc: '/explore.html', changefreq: 'daily', priority: 0.9 },{ loc: '/profile.html', changefreq: 'daily', priority: 0.9 },75 unmodified lines7677787980818283295 unmodified lines379380381382383384385386726 unmodified lines1113111411151116111711181119112011211122112311241125112611271128112911303222 unmodified lines4353435443554356435743584359436043614362436343642 unmodified lines43674368436943704371437243735922 unmodified lines102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311 unmodified line1043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045416 unmodified lines1047110472104731047410475104761047724 unmodified lines105021050310504105051050610507105086 unmodified lines105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511 unmodified line10553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109298081 unmodified lines19011190121901319014190151901619017190181901919020190211902256 unmodified lines19079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910517464 unmodified lines3657036571365723657336574365753657675 unmodified linesconst app = express();app.set('trust proxy', true);const getSocketClient = require('./utils/socket-client');app.use(cors({295 unmodified lines'/api/subscription/renew','/api/subscription/cancel','/api/users/:userId/badges','/api/profile/:userId/view','/api/achievements/:slug','/api/users/:userId','/api/admin/stores/:userId/toggle','/api/admin/stores/:userId',726 unmodified lines// ============================================const messageUpload = multer({storage: multer.memoryStorage(),limits: { fileSize: 10 * 1024 * 1024 },fileFilter: (req, file, cb) => {const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp','video/mp4', 'video/webm', 'video/ogg','application/pdf','audio/mpeg', 'audio/webm', 'audio/mp4', 'audio/ogg'];if (allowedTypes.includes(file.mimetype)) {cb(null, true);} else {cb(new Error('File type not allowed. Allowed: images, videos, PDF, audio'), false);}}});3222 unmodified linesinteraction: {bronze: { type: Boolean, default: false }, // 10 ردود},ratings: {bronze: { type: Boolean, default: false },silver: { type: Boolean, default: false },gold: { type: Boolean, default: false },platinum: { type: Boolean, default: false }},unlockedAt: { type: Date, default: null },updatedAt: { type: Date, default: Date.now }},2 unmodified lineslikes: { bronze: false, silver: false, gold: false, red: false },interaction: { bronze: false },unlockedAt: null,ratings: { bronze: false, silver: false, gold: false, platinum: false },updatedAt: Date.now}},5922 unmodified lines}});// ============================================// POST /api/profile/:userId/view - تتبع مشاهدة البروفايل// ============================================app.post('/api/profile/:userId/view', async (req, res) => {try {const { userId: targetUserId } = req.params;if (!targetUserId) {return res.status(400).json({success: false,error: 'targetUserId is required'});}// ✅ الحصول على viewerId من التوكن (لو موجود)const viewerId = req.user?.userId || null;const viewerIp = req.ip || req.connection?.remoteAddress || 'unknown';// ✅ لا تسجل مشاهدة لنفس المستخدمif (viewerId === targetUserId) {return res.json({success: true,message: 'Self view not tracked',data: { selfView: true }});}// ============================// 📊 1. تسجيل في ProfileAnalytics// ============================let analytics = await ProfileAnalytics.findOne({ userId: targetUserId });if (!analytics) {analytics = new ProfileAnalytics({ userId: targetUserId });}analytics.profileViews = analytics.profileViews || [];analytics.profileViews.push({viewerId: viewerId,viewerIp: viewerIp,viewedAt: new Date()});// ✅ الاحتفاظ بآخر 100 مشاهدة فقطif (analytics.profileViews.length > 100) {analytics.profileViews = analytics.profileViews.slice(-100);}analytics.lastUpdated = new Date();await analytics.save();// ============================// 👥 2. تسجيل في AlsoViewed// ============================if (viewerId) {// ✅ مستخدم مسجلawait AlsoViewed.findOneAndUpdate({ targetUserId, viewerId: viewerId },{viewedAt: new Date(),viewerIp: viewerIp},{ upsert: true });} else {// ✅ زائر (غير مسجل) - نستخدم IPconst existingView = await AlsoViewed.findOne({targetUserId,viewerIp: viewerIp,viewedAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }});if (!existingView) {await AlsoViewed.create({targetUserId,viewerId: null,viewerIp: viewerIp,viewedAt: new Date()});}}// ============================// 🏆 3. تحديث البرونزيات// ============================const badgeResult = await updateUserBadges(targetUserId);// ============================// 📢 4. بث للمستخدم المستهدف (لو فتح برونزية) - عبر Socket// ============================if (badgeResult?.newBadgeUnlocked && badgeResult?.unlockedBadges?.length > 0) {// ✅ استخدم io.to (نفس الكود القديم)io.to(`user_${targetUserId}`).emit('badge_unlocked', {userId: targetUserId,badges: badgeResult.unlockedBadges,badgeIcons: badgeResult.unlockedBadgeIcons || [],viewCount: badgeResult.viewCount,likeCount: badgeResult.likeCount,replyCount: badgeResult.replyCount,ratingCount: badgeResult.ratingCount,totalBadges: badgeResult.totalBadgeCount});}res.json({success: true,message: 'View tracked successfully',data: {viewCount: badgeResult?.viewCount || 0,likeCount: badgeResult?.likeCount || 0,replyCount: badgeResult?.replyCount || 0,ratingCount: badgeResult?.ratingCount || 0,totalBadges: badgeResult?.totalBadgeCount || 0,newBadgeUnlocked: badgeResult?.newBadgeUnlocked || false,unlockedBadges: badgeResult?.unlockedBadges || []}});} catch (error) {console.error('❌ Track profile view error:', error);// ✅ لا نرسل خطأ للمستخدم حتى لا يسبب مشاكلres.json({success: true,message: 'View tracked',data: { error: error.message }});}});// ============================================// GET /api/users/:userId/badges - جلب البرونزيات المفتوحة فقط// ============================================1 unmodified linetry {const { userId } = req.params;// ✅ جلب جميع البيانات بشكل متوازي (نفس الـ Socket)const [badges, viewCount, likeCount, replyCount, ratingCount] = await Promise.all([getUserBadges(userId),getUniqueViewsCount(userId),getTotalPostLikes(userId),getTotalUserReplies(userId),getTotalUserRatings(userId) // ✅ أضف ratingCount]);// ✅ حساب التالي - نفس منطق الـ Socket بالضبطlet nextBadge = null;let nextThreshold = null;let progress = 100;let nextBadgeType = null;// ✅ Views Badgesconst viewsBadges = badges.views || { unlocked: [], count: 0 };const hasSilver = viewsBadges.unlocked.some(b => b.key === 'silver');const hasGold = viewsBadges.unlocked.some(b => b.key === 'gold');16 unmodified linesnextBadgeType = 'views';}// ✅ Likes Badgesconst likesBadges = badges.likes || { unlocked: [], count: 0 };const hasLikesBronze = likesBadges.unlocked.some(b => b.key === 'bronze');const hasLikesRed = likesBadges.unlocked.some(b => b.key === 'red');24 unmodified lines}}// ✅ Interaction Badgesconst interactionBadges = badges.interaction || { unlocked: [], count: 0 };const hasInteractionBronze = interactionBadges.unlocked.some(b => b.key === 'bronze');6 unmodified lines}}// ✅ Ratings Badgesconst ratingsBadges = badges.ratings || { unlocked: [], count: 0 };const hasRatingsBronze = ratingsBadges.unlocked.some(b => b.key === 'bronze');const hasRatingsSilver = ratingsBadges.unlocked.some(b => b.key === 'silver');const hasRatingsGold = ratingsBadges.unlocked.some(b => b.key === 'gold');const hasRatingsPlatinum = ratingsBadges.unlocked.some(b => b.key === 'platinum');if (!nextBadge) {if (!hasRatingsBronze && ratingCount < RATING_BADGE_THRESHOLDS.BRONZE) {nextBadge = 'Ratings Bronze';nextThreshold = RATING_BADGE_THRESHOLDS.BRONZE;progress = (ratingCount / RATING_BADGE_THRESHOLDS.BRONZE) * 100;nextBadgeType = 'ratings';} else if (!hasRatingsSilver && ratingCount < RATING_BADGE_THRESHOLDS.SILVER) {nextBadge = 'Ratings Silver';nextThreshold = RATING_BADGE_THRESHOLDS.SILVER;progress = (ratingCount / RATING_BADGE_THRESHOLDS.SILVER) * 100;nextBadgeType = 'ratings';} else if (!hasRatingsGold && ratingCount < RATING_BADGE_THRESHOLDS.GOLD) {nextBadge = 'Ratings Gold';nextThreshold = RATING_BADGE_THRESHOLDS.GOLD;progress = (ratingCount / RATING_BADGE_THRESHOLDS.GOLD) * 100;nextBadgeType = 'ratings';} else if (!hasRatingsPlatinum && ratingCount < RATING_BADGE_THRESHOLDS.PLATINUM) {nextBadge = 'Ratings Platinum';nextThreshold = RATING_BADGE_THRESHOLDS.PLATINUM;progress = (ratingCount / RATING_BADGE_THRESHOLDS.PLATINUM) * 100;nextBadgeType = 'ratings';}}if (!nextBadge) {nextBadge = 'All badges collected! 🎉';nextThreshold = null;1 unmodified linenextBadgeType = 'complete';}const totalBadges = badges.totalCount || 0;const totalPossible = 3 + 4 + 1 + 4; // views(3) + likes(4) + interaction(1) + ratings(4)const overallProgress = Math.min((totalBadges / totalPossible) * 100, 100);// ✅ نفس بنية البيانات تماماً زي الـ Socketres.json({success: true,data: {userId,viewCount,likeCount,replyCount,ratingCount,badges: {views: {unlocked: badges.views?.unlocked || [],count: badges.views?.count || 0},likes: {unlocked: badges.likes?.unlocked || [],count: badges.likes?.count || 0},interaction: {unlocked: badges.interaction?.unlocked || [],count: badges.interaction?.count || 0},ratings: {unlocked: badges.ratings?.unlocked || [],count: badges.ratings?.count || 0},unlocked: badges.unlocked || [],totalCount: totalBadges},thresholds: {views: VIEW_BADGE_THRESHOLDS,likes: LIKE_BADGE_THRESHOLDS,interaction: INTERACTION_BADGE_THRESHOLDS,ratings: RATING_BADGE_THRESHOLDS},nextBadge,nextThreshold,nextBadgeType,progress: Math.min(Math.round(progress), 100),overallProgress: Math.min(Math.round(overallProgress), 100),totalBadges,totalPossible}});} catch (error) {console.error('Error getting badges:', error);res.status(500).json({success: false,error: 'Failed to get badges'});}});// ============================================// GET /api/achievements/:slug - جلب تفاصيل برونزية معينة// ============================================app.get('/api/achievements/:slug', async (req, res) => {try {const { slug } = req.params;const { userId } = req.query; // ✅ userId من query string// ✅ تعريف كل البرونزيات مع بياناتها الكاملةconst achievements = {'views-silver': {name: 'Views Silver',slug: 'views-silver',icon: '/assets/img/fire.svg',type: 'views',description: 'Achieved 20 unique profile views. Your profile is getting noticed!',rarity: 'uncommon',rarityScore: 15,threshold: 20,requirements: [{ text: 'Get 20 unique profile views', max: 20 }]},'views-gold': {name: 'Views Gold',slug: 'views-gold',icon: '/assets/img/firegolden.svg',type: 'views',description: 'Achieved 100 unique profile views. You\'re building a strong presence!',rarity: 'rare',rarityScore: 30,threshold: 100,requirements: [{ text: 'Get 100 unique profile views', max: 100 }]},'views-red': {name: 'Views Red',slug: 'views-red',icon: '/assets/img/firered.svg',type: 'views',description: 'Achieved 200 unique profile views. You\'re a rising star!',rarity: 'epic',rarityScore: 50,threshold: 200,requirements: [{ text: 'Get 200 unique profile views', max: 200 }]},'likes-bronze': {name: 'Likes Bronze',slug: 'likes-bronze',icon: '/assets/img/StarStruck_SkinTone1.png',type: 'likes',description: 'Received 10 likes across your posts. People appreciate your content!',rarity: 'common',rarityScore: 5,threshold: 10,requirements: [{ text: 'Receive 10 likes on your posts', max: 10 }]},'likes-red': {name: 'Likes Red',slug: 'likes-red',icon: '/assets/img/StarStruck_Bronze.png',type: 'likes',description: 'Received 128 likes across your posts. Your content is gaining traction!',rarity: 'uncommon',rarityScore: 20,threshold: 128,requirements: [{ text: 'Receive 128 likes on your posts', max: 128 }]},'likes-silver': {name: 'Likes Silver',slug: 'likes-silver',icon: '/assets/img/StarStruck_Silver.png',type: 'likes',description: 'Received 512 likes across your posts. You\'re building a strong community!',rarity: 'rare',rarityScore: 35,threshold: 512,requirements: [{ text: 'Receive 512 likes on your posts', max: 512 }]},'likes-gold': {name: 'Likes Gold',slug: 'likes-gold',icon: '/assets/img/StarStruck_Gold.png',type: 'likes',description: 'Received 4096 likes across your posts. Your content is going viral!',rarity: 'epic',rarityScore: 60,threshold: 4096,requirements: [{ text: 'Receive 4096 likes on your posts', max: 4096 }]},'interaction-bronze': {name: 'Interaction Bronze',slug: 'interaction-bronze',icon: '/assets/img/QuickDraw_SkinTone1.png',type: 'interaction',description: 'Replied to 10 comments. You\'re an active community member!',rarity: 'common',rarityScore: 5,threshold: 10,requirements: [{ text: 'Reply to 10 comments on other posts', max: 10 }]},'ratings-bronze': {name: 'Ratings Bronze',slug: 'ratings-bronze',icon: '/assets/img/GalaxyBrain.png',type: 'ratings',description: 'Received 2 ratings. Your work is being recognized!',rarity: 'common',rarityScore: 5,threshold: 2,requirements: [{ text: 'Receive 2 ratings on your profile', max: 2 }]},'ratings-silver': {name: 'Ratings Silver',slug: 'ratings-silver',icon: '/assets/img/GalaxyBrain_Bronze.png',type: 'ratings',description: 'Received 6 ratings. Your reputation is growing!',rarity: 'uncommon',rarityScore: 15,threshold: 6,requirements: [{ text: 'Receive 6 ratings on your profile', max: 6 }]},'ratings-gold': {name: 'Ratings Gold',slug: 'ratings-gold',icon: '/assets/img/GalaxyBrain_Silver.png',type: 'ratings',description: 'Received 16 ratings. You\'re highly regarded by the community!',rarity: 'rare',rarityScore: 30,threshold: 16,requirements: [{ text: 'Receive 16 ratings on your profile', max: 16 }]},'ratings-platinum': {name: 'Ratings Platinum',slug: 'ratings-platinum',icon: '/assets/img/GalaxyBrain_Gold.png',type: 'ratings',description: 'Received 32 ratings. You\'re a top-rated professional!',rarity: 'epic',rarityScore: 55,threshold: 32,requirements: [{ text: 'Receive 32 ratings on your profile', max: 32 }]}};const achievement = achievements[slug];if (!achievement) {return res.status(404).json({success: false,error: 'Achievement not found'});}// ✅ جلب إحصائيات فعلية من قاعدة البياناتlet userUnlocked = false;let userUnlockedAt = null;let progress = 0;let currentValue = 0;let requirements = [];let stats = [];let usersEarnedList = [];// ✅ استخدام userId من الـ queryconst targetUserId = userId || req.user?.userId || null;console.log(`🔍 Achievement details requested: ${slug}, userId: ${targetUserId}`);if (targetUserId) {// ✅ جلب بيانات المستخدمconst user = await User.findById(targetUserId).select('profile.badges');if (user && user.profile?.badges) {const badges = user.profile.badges;// ✅ التحقق من فتح البرونزية وحساب التقدمconst badgeType = achievement.type;const threshold = achievement.threshold || 0;// ✅ جلب القيمة الفعلية حسب النوعif (badgeType === 'views') {currentValue = await getUniqueViewsCount(targetUserId);} else if (badgeType === 'likes') {currentValue = await getTotalPostLikes(targetUserId);} else if (badgeType === 'interaction') {currentValue = await getTotalUserReplies(targetUserId);} else if (badgeType === 'ratings') {currentValue = await getTotalUserRatings(targetUserId);}progress = Math.min((currentValue / threshold) * 100, 100);// ✅ التحقق من الفتحconst badgeKey = slug.split('-').pop(); // silver, gold, red, bronze, platinumlet isUnlocked = false;if (badgeType === 'views' && badges.views) {isUnlocked = badges.views[badgeKey] === true;} else if (badgeType === 'likes' && badges.likes) {isUnlocked = badges.likes[badgeKey] === true;} else if (badgeType === 'interaction' && badges.interaction) {isUnlocked = badges.interaction[badgeKey] === true;} else if (badgeType === 'ratings' && badges.ratings) {isUnlocked = badges.ratings[badgeKey] === true;}console.log(`📊 Achievement check:`, {slug,badgeType,badgeKey,isUnlocked,currentValue,threshold,userBadges: badges[badgeType]});if (isUnlocked) {userUnlocked = true;userUnlockedAt = badges.unlockedAt || new Date();}}// ✅ جلب المستخدمين الذين حصلوا على هذه البرونزيةconst allUsers = await User.find({[`profile.badges.${achievement.type}.${slug.split('-').pop()}`]: true}).select('username profile.nickname profile.avatar profile.badges.unlockedAt').limit(10).lean();usersEarnedList = allUsers.map(u => ({name: u.profile?.nickname || u.username,nickname: u.profile?.nickname || u.username,username: u.username,avatar: u.profile?.avatar || '/assets/img/default-avatar.png',unlockedAt: u.profile?.badges?.unlockedAt || null}));}// ✅ بناء الـ Requirements مع التقدم الفعليrequirements = achievement.requirements.map(req => ({...req,progress: Math.min(currentValue, req.max),completed: currentValue >= req.max}));// ✅ بناء الإحصائياتstats = [{ label: 'Progress', value: `${Math.round(progress)}%`, icon: 'bx-chart' },{ label: 'Current', value: currentValue, icon: 'bx-current-location' },{ label: 'Target', value: achievement.threshold || '—', icon: 'bx-bullseye' },{ label: 'Status', value: userUnlocked ? '✅ Unlocked' : '🔒 In Progress', icon: 'bx-info-circle' }];// ✅ بناء البيانات النهائية (نفس هيكل الـ Socket)const responseData = {...achievement,isUnlocked: userUnlocked,unlockedAt: userUnlockedAt,progress: Math.min(currentValue, achievement.threshold || 0),maxProgress: achievement.threshold || 0,currentValue: currentValue,requirements: requirements,stats: stats,usersEarnedList: usersEarnedList,totalEarned: usersEarnedList.length,globalRank: usersEarnedList.length > 0 ? `#${Math.floor(Math.random() * 100) + 1}` : '#N/A'};console.log(`✅ Achievement response:`, {name: responseData.name,isUnlocked: responseData.isUnlocked,currentValue: responseData.currentValue,maxProgress: responseData.maxProgress});res.json({success: true,data: responseData});} catch (error) {console.error('❌ Achievement details error:', error);res.status(500).json({success: false,error: error.message});}});// ============================================// GET /api/users/:userId - جلب بيانات مستخدم معين للوسام8081 unmodified linesuploadStream.end(file.buffer);});let attachmentType = 'file';if (file.mimetype.startsWith('image/')) attachmentType = 'image';else if (file.mimetype.startsWith('video/')) attachmentType = 'video';else if (file.mimetype.startsWith('audio/')) attachmentType = 'audio';else if (file.mimetype === 'application/pdf') attachmentType = 'pdf';else attachmentType = 'file';attachments.push({type: attachmentType,56 unmodified linesconst populatedMessage = await message.populate('senderId', 'username profile.nickname profile.avatar');try {const socketClient = getSocketClient(); // يجب استيرادها من ملف منفصل// بث الرسالة لكل من في غرفة المحادثةsocketClient.to(`conv_${conversationId}`).emit('new_message', populatedMessage);// إرسال إشعار للمستلمsocketClient.to(`user_${otherParticipant}`).emit('new_message_notification', {conversationId,sender: {id: req.user.userId,username: sender.profile?.nickname || sender.username,avatar: sender.profile?.avatar},message: populatedMessage});logger.info(`📢 Broadcasted message ${populatedMessage._id} via Socket.IO`);} catch (socketError) {// لا نوقف الـ response إذا فشل البث، فقط نسجل الخطأlogger.error(`Socket broadcast failed: ${socketError.message}`);}res.status(201).json({ success: true, data: populatedMessage });} catch (error) {17464 unmodified lines{ loc: '/feed.html', changefreq: 'daily', priority: 0.9 },{ loc: '/videos.html', changefreq: 'daily', priority: 0.9 },{ loc: '/video.html', changefreq: 'daily', priority: 0.9 },{ loc: '/achievement.html', changefreq: 'daily', priority: 0.9 },{ loc: '/template-store.html', changefreq: 'daily', priority: 0.9 },{ loc: '/explore.html', changefreq: 'daily', priority: 0.9 },{ loc: '/profile.html', changefreq: 'daily', priority: 0.9 },
1234567891011121314151617181920212223242526272829303132const io = require('socket.io-client');
const SOCKET_SERVER_URL = process.env.SOCKET_SERVER_URL || 'https://al-asfar-mgzon-socket-server.hf.space';
let socketClient = null;
function getSocketClient() { if (!socketClient) { socketClient = io(SOCKET_SERVER_URL, { transports: ['websocket', 'polling'], reconnection: true, reconnectionAttempts: 10, reconnectionDelay: 1000, reconnectionDelayMax: 5000, });
socketClient.on('connect', () => { console.log('✅ REST API connected to Socket.IO server'); });
socketClient.on('connect_error', (err) => { console.error('❌ REST API Socket.IO connection error:', err.message); });
socketClient.on('disconnect', () => { console.warn('⚠️ REST API disconnected from Socket.IO server'); }); } return socketClient;}
module.exports = getSocketClient;package-lock.json+155
package.json+1
server.js+566-45
utils/socket-client.jsAdded+32